﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Retail.Models.DBModels;
using RetailService.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using test;
using Yunzuan.Common;
using Yunzuan.Common.Interface;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Log;
using Yunzuan.Foundation.Serializer;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;

namespace RetailService
{
    public class Retail : IRetail
    {
        /// <summary>
        /// 方法原始参数：logParam
        /// </summary>
        string logParam;
        const string _logTemplate = "方法名：{0}，参数名：{1}，行号：{2} ,参数值：{3}";

        public Dictionary<string, string> addNull = new Dictionary<string, string>();


        /// <summary>
        /// 上传模式（0覆盖 1追加）
        /// </summary>
        public string UploadFileState(string uploadFileStateParam)
        {
            return AllPublic.UploadFileState(uploadFileStateParam);
        }
        public string ModifyExchange(string modifyExchangeParam)
        {
            return AllPublic.ModifyExchange(modifyExchangeParam);
        }
        #region  祼钻订单相关



        /// <summary>
        /// 单个订单改价(单个操作 卖出退点 卖出RMB)
        /// </summary>
        /// <param name="reviseOrderParam"></param>
        /// <returns></returns>
        public string ReviseAnOrder(string reviseAnOrderParam)
        {
            logParam = reviseAnOrderParam;
            HashParam param = Json.Deserialize<HashParam>(reviseAnOrderParam);//前端传过来要改变的值
            string tttagKey = CommonUrl.getURL(param, reviseAnOrderParam);
            //OrderID（必传）、SalesExchangerate(默认值)、Confirmdiscount、ConfirmPrice(二选一)
            try
            {
                if (param.GetInt("OrderID") == null || param.GetInt("OrderID") == 0)
                {
                    return CommonLog.MsgErrorInfo("改价失败，订单标识不存在");
                }
                //OrderInfo _order = YZ.GetDatabase(tttagKey).Get<OrderInfo>(param.GetInt("OrderID"));//坑
                OrderNewLS _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderNewLS>("Order.GetOrderByID", param);
                InventoryResult _inventory = JsonConvert.DeserializeObject<InventoryResult>(_order.InventoryAttribute);
                if (_order != null)
                {
                    //反推(卖出退点或卖出人民币总价)
                    //白钻：重量*RAP*（卖出退点_confirmdiscount）*（销售汇率_salesExchangerate） = 卖出人民币总价（_confirmPrice）
                    //彩钻：重量*（卖出退点_confirmdiscount）*（销售汇率_salesExchangerate） = 卖出人民币总价（_confirmPrice）
                    try
                    {
                        //为了保险，重新获取RAPNET （4C）
                        RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                        //包货
                        if (_inventory.CertType == "PARCEL")
                        {
                            _order.Rapnet = 0;//无Rapnet
                        }
                        else
                        {
                            _order.Rapnet = rap.GetPrice(_order);
                        }
                    }
                    catch (Exception ex)
                    {
                        GetMethodInfoAndWriteLogs(ex);
                        return CommonLog.MsgErrorInfo("价格推算失败，程序错误");
                    }
                    int? _mode = param.GetInt("Mode");//1优惠退点 0优惠折扣
                    decimal _salesExchangerate = Convert.ToDecimal(param.GetString("SalesExchangerate"));//销售汇率(默认选择系统)
                    if (_mode == 0)
                    {
                        decimal _confirmPrice = Convert.ToDecimal(param.GetString("ConfirmPrice"));//卖出人民币总价
                        //总价法
                        if (_confirmPrice != 0 && _salesExchangerate != 0)
                        {
                            if (_inventory.IsFancy == 0)
                            {
                                //通过卖出人民币总价推算卖出退点                   
                                _order.ConfirmPrice = _confirmPrice;
                                _order.Confirmdiscount = (((decimal)(_order.ConfirmPrice) / ((decimal)_inventory.Weight * (decimal)_order.Rapnet * (decimal)_salesExchangerate)) + (-1)) * 100;
                                _order.SalesExchangerate = _salesExchangerate;
                                _order.ConfirmUSD = _confirmPrice / _salesExchangerate;//卖出美金 2017-01-11
                            }
                            else
                            {
                                _order.Confirmdiscount = 0;//彩钻无卖出退点
                                _order.ConfirmPrice = _confirmPrice;
                                _order.SalesExchangerate = _salesExchangerate;//10-26修复
                                _order.ConfirmUSD = _confirmPrice / _salesExchangerate;//卖出美金 2017-01-11
                            }
                        }
                        else
                        {
                            //人民币总价为0
                            return CommonLog.MsgErrorInfo("改价失败:汇率和总价不能为0");
                        }
                    }
                    else
                    {
                        decimal _confirmdiscount = Convert.ToDecimal(param.GetString("Confirmdiscount"));//卖出退点
                        //退点法
                        if (_salesExchangerate != 0)
                        {
                            if (_inventory.IsFancy == 0)
                            {
                                //通过卖出退点推算卖出人民币总价  
                                _order.Confirmdiscount = _confirmdiscount;
                                _order.ConfirmPrice = (decimal)_inventory.Weight * (decimal)_order.Rapnet * (decimal)((100 + _confirmdiscount) / 100) * (decimal)_salesExchangerate;
                                _order.SalesExchangerate = _salesExchangerate;//10-26修复
                                _order.ConfirmUSD = _order.ConfirmPrice / _salesExchangerate;//卖出美金 2017-01-11
                            }
                            else
                            {
                                //彩钻退点法 无意义
                                return CommonLog.MsgErrorInfo("改价失败，彩钻应修改总价");
                            }
                        }
                        else
                        {
                            //退点为0
                            return CommonLog.MsgErrorInfo("改价失败:汇率不能为0");
                        }
                    }
                    //执行
                    using (ITransaction trans_reviseAnOrder = YZ.GetTransaction(tttagKey))
                    {
                        int reviseAnOrderResult = trans_reviseAnOrder.Edit(_order);
                        if (reviseAnOrderResult > 0)
                        {
                            try
                            {
                                trans_reviseAnOrder.CommitTransaction(); //触发入库事务
                            }
                            catch (Exception)
                            {
                                trans_reviseAnOrder.RollBackTransaction();//回滚事务
                            }
                            return CommonLog.MsgSuccessInfo("改价成功");
                        }
                        return CommonLog.MsgErrorInfo("改价失败");
                    }
                }
                return CommonLog.MsgErrorInfo("改价失败，订单标识不存在");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("改价失败，程序错误");
            }
        }




        /// <summary>
        /// 出货
        /// </summary>
        /// <param name="editShipParam"></param>
        /// <returns></returns>
        public string EditShip(string editShipParam)
        {
            logParam = editShipParam;
            HashParam param = Json.Deserialize<HashParam>(editShipParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, editShipParam);
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                if (_orderIDs.Length > 0)
                {
                    OrderInfo _order = new OrderInfo();
                    _order.OrderStatus = 4;//4已出货
                    _order.ShipRemarks = param.GetString("ShipRemarks").Replace(" ", "");//出货备注
                    _order.ShipTime = DateTime.Now;//出货时间
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        _order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID
                        using (ITransaction trans_editShip = YZ.GetTransaction(tttagKey))
                        {
                            int editShipResult = trans_editShip.Edit(_order);
                            //单条成功后，就执行入库订单事务
                            if (editShipResult > 0)
                            {
                                try
                                {
                                    trans_editShip.CommitTransaction(); //触发入库事务
                                }
                                catch (Exception)
                                {
                                    trans_editShip.RollBackTransaction();//回滚事务
                                }
                            }
                        }
                    }
                    return CommonLog.MsgSuccessInfo("出货成功");//不考虑OrderID不存在的情况
                }
                else
                {
                    return CommonLog.MsgErrorInfo("出货失败，没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("出货，程序错误");
            }
        }

        /// <summary>
        /// 退回订单
        /// </summary>
        /// <param name="stockOrdersParam"></param>
        /// <returns></returns>
        public string ReturnOrders1(string returnOrdersParam)
        {
            logParam = returnOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(returnOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, returnOrdersParam);
            //(不足：不考虑OrderID不存在的情况,没有判断OrderID是否真实)
            //OrderIDs、SalesRemarks 取消理由(1我不想买了；2误下单，重新拍；3缺货；4货品与实际描述不符；5价格贵；)
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                if (_orderIDs.Length == 0)
                {
                    return CommonLog.MsgErrorInfo("没选择任何订单");
                }
                OrderInfo _order = new OrderInfo();
                for (int i = 0; i < _orderIDs.Length; i++)
                {
                    _order.OrderID = Convert.ToInt32(_orderIDs[i]);
                    _order.OrderStatus = 7;//退回订单 （7 已退回）
                    _order.SalesRemarks = param.GetString("SalesRemarks").Replace(" ", "");//业务作废备注
                    try
                    {
                        using (ITransaction trans_returnOrders = YZ.GetTransaction(tttagKey))
                        {
                            int returnOrdersResult = trans_returnOrders.Edit(_order);
                            //单条成功后，就执行作废订单事务
                            if (returnOrdersResult > 0)
                            {
                                try
                                {
                                    trans_returnOrders.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                                }
                                catch (Exception)
                                {
                                    trans_returnOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                Logger.Error(this.GetType(), "失败:订单标识不存在");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        GetMethodInfoAndWriteLogs(ex);
                        return CommonLog.MsgErrorInfo("失败，程序错误");
                    }
                }
                return CommonLog.MsgSuccessInfo("退回成功");//缺点：没有考虑OrderID不存在的情况
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 自留订单
        /// </summary>
        /// <param name="cancelOrdersParam"></param>
        /// <returns></returns>
        public string StockOrders1(string stockOrdersParam)
        {
            logParam = stockOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(stockOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, stockOrdersParam);
            //(不足：不考虑OrderID不存在的情况,没有判断OrderID是否真实)
            //OrderIDs、SalesRemarks 取消理由(1我不想买了；2误下单，重新拍；3缺货；4货品与实际描述不符；5价格贵；)
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                if (_orderIDs.Length == 0)
                {
                    return CommonLog.MsgErrorInfo("自留失败，没选择任何订单");
                }
                OrderInfo _order = new OrderInfo();
                for (int i = 0; i < _orderIDs.Length; i++)
                {
                    _order.OrderID = Convert.ToInt32(_orderIDs[i]);
                    _order.OrderStatus = 6;//自留订单 （6 已自留）
                    _order.SalesRemarks = param.GetString("SalesRemarks").Replace(" ", "");//业务作废备注
                    try
                    {
                        using (ITransaction trans_stockOrders = YZ.GetTransaction(tttagKey))
                        {
                            int stockOrdersResult = trans_stockOrders.Edit(_order);
                            //单条成功后，就执行作废订单事务
                            if (stockOrdersResult > 0)
                            {
                                try
                                {
                                    trans_stockOrders.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                                }
                                catch (Exception)
                                {
                                    trans_stockOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                Logger.Error(this.GetType(), "自留失败:订单标识不存在");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        GetMethodInfoAndWriteLogs(ex);
                        return CommonLog.MsgErrorInfo("自留失败，程序错误");
                    }
                }
                return CommonLog.MsgSuccessInfo("自留成功");//缺点：没有考虑OrderID不存在的情况
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("自留失败，程序错误");
            }
        }

        //转移客户 9-24
        public string ModifySalesUserID(string modifySalesUserIDParam)
        {
            logParam = modifySalesUserIDParam;
            HashParam param = Json.Deserialize<HashParam>(modifySalesUserIDParam);
            string tttagKey = CommonUrl.getURL(param, modifySalesUserIDParam);
            //OrderIDs、PurchaseUserID (不足：不考虑OrderID不存在的情况,没有判断OrderID是否真实)
            try
            {
                string[] _customerIDs = param.GetString("CustomerIDs").Split(',');
                if (_customerIDs.Length == 0)
                {
                    return CommonLog.MsgErrorInfo("移交失败,没选择任何客户");
                }
                CustomerInfo _customer = new CustomerInfo();
                for (int i = 0; i < _customerIDs.Length; i++)
                {
                    _customer.CustomerID = Convert.ToInt32(_customerIDs[i]);
                    _customer.SalesUserID = param.GetInt("SalesUserID").Value;//业务ID(必传字段)
                    try
                    {
                        using (ITransaction trans_ModifySalesUserID = YZ.GetTransaction(tttagKey))
                        {
                            int _modifySalesUserIDResult = trans_ModifySalesUserID.Edit(_customer);
                            //单条成功后，就执行转移订单事务
                            if (_modifySalesUserIDResult > 0)
                            {
                                try
                                {
                                    trans_ModifySalesUserID.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                                }
                                catch (Exception)
                                {
                                    trans_ModifySalesUserID.RollBackTransaction();//回滚事务
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        GetMethodInfoAndWriteLogs(ex);
                        return CommonLog.MsgErrorInfo("移交失败");
                    }
                }
                return CommonLog.MsgSuccessInfo("移交成功");//不考虑CustomerID不存在的情况
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("移交失败");
            }
        }
        /// <summary>
        /// 转移订单（修改采购）--含事务        （不改变订单状态）
        /// </summary>
        /// <param name="modifyPurchaseUserIDParam"></param>
        /// <returns></returns>
        public string ModifyPurchaseUserID(string modifyPurchaseUserIDParam)
        {
            logParam = modifyPurchaseUserIDParam;
            HashParam param = Json.Deserialize<HashParam>(modifyPurchaseUserIDParam);
            string tttagKey = CommonUrl.getURL(param, modifyPurchaseUserIDParam);
            //OrderIDs、PurchaseUserID (不足：不考虑OrderID不存在的情况,没有判断OrderID是否真实)
            try
            {
                if (param.GetString("OrderIDs") != "")
                {
                    string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                    OrderInfo _order = new OrderInfo();
                    using (ITransaction trans_ModifyPurchaseUserID = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            _order.OrderID = Convert.ToInt32(_orderIDs[i]);
                            _order.PurchaseUserID = param.GetInt("PurchaseUserID").Value;//采购ID(必传字段)
                            int _modifyPurchaseUserIDResult = trans_ModifyPurchaseUserID.Edit(_order);
                            //单条成功后，就执行转移订单事务
                            if (_modifyPurchaseUserIDResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("转移失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_ModifyPurchaseUserID.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("转移成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_ModifyPurchaseUserID.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("转移失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("转移失败,请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 订单列表(客户和团队)  -- 纯粹读数据 无需 事务
        /// </summary>
        /// <param name="getOrdersParam"></param>
        /// <returns></returns>
        public string GetOrders(string getOrdersParam)
        {
            logParam = getOrdersParam;
            string tttagKey = CommonUrl.getURL(null, getOrdersParam);
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(getOrdersParam);
            try
            {
                var _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrders", param, param.pageSize, param.pageIndex);
                if (_ordersInfo != null && _ordersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败");
            }
        }

        /// <summary>
        /// 退回供应商收款
        /// </summary>
        /// <returns></returns>
        public string PayBackOrders(string paybackOrdersParam)
        {
            logParam = paybackOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(paybackOrdersParam);
            string tttagKey = CommonUrl.getURL(param, paybackOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.ReceiptStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? totalRMB = 0, totalUSD = 0;
                            BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("BankID"));
                            if (_bank != null)
                            {
                                _bank.BankBalance = _bank.BankBalance + param.GetDecimal("PayBackAmount");
                                _bank.UpdateTime = DateTime.Now;//账户结余更新时间
                                //更新账户结余
                                #region
                                int editBalanceResult = trans_payOrders.Edit(_bank);//更新客户余额事务 要用Edit 12-10
                                if (editBalanceResult > 0)
                                {
                                    //更新订单付款状态
                                    #region
                                    for (int i = 0; i < OrderList.Count; i++)
                                    {
                                        //已付1
                                        if (OrderList[i].ReceiptStatus == 1)
                                        {
                                            totalRMB += OrderList[i].PurchaseRMB;
                                            totalUSD += OrderList[i].PriceUSD;
                                            OrderList[i].ReceiptStatus = 0;//支付状态(1已支付 0 未支付)
                                            OrderList[i].RecTime = null;//支付时间
                                            OrderList[i].CurType = null;//结算币种
                                            int editOrderResult = trans_payOrders.Edit(OrderList[i]);//更新订单支付状态
                                            if (editOrderResult > 0)
                                            {
                                                //继续
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("订单不存在");
                                            }
                                        }
                                    }
                                    #endregion
                                    //生成流水
                                    #region
                                    if (totalRMB > 0 || totalUSD > 0)
                                    {
                                        FlowInfo _flow = new FlowInfo();
                                        _flow.CreateTime = DateTime.Now;
                                        _flow.UpdateTime = DateTime.Now;
                                        _flow.Amount = param.GetDecimal("PayBackAmount");
                                        if (_bank.Currency == 1)
                                        {
                                            _flow.Receivable = totalRMB;
                                        }
                                        else if (_bank.Currency == 2)
                                        {
                                            _flow.Receivable = totalUSD;
                                        }
                                        _flow.Balance = _bank.BankBalance;
                                        _flow.Currency = _bank.Currency;
                                        _flow.Account = _bank.BankID;
                                        _flow.Type = 1;//1收入
                                        _flow.Abstract = 3;//3退供应商
                                        _flow.OrderIDs = param.GetString("OrderIDs");
                                        _flow.ApplyID = param.GetInt("ApplyID");
                                        _flow.ReviewID = param.GetInt("ApplyID");
                                        _flow.ArrivalTime = param.GetDataTime("ArrivalTime");
                                        _flow.Remarks = "应收" + totalRMB + "￥或" + totalUSD + "$";
                                        _flow.Comments = "实收" + param.GetDecimal("PayBackAmount") + "";
                                        _flow.Status = 1;
                                        _flow.Purpose = 0;
                                        int addFlowResult = trans_payOrders.Add(_flow);
                                        if (addFlowResult > 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("生成流水失败");
                                        }
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("订单全部未付,不用收款");
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("账户不存在");
                                }
                                #endregion
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("账户不存在,检查账户标识");
                            }
                            try
                            {
                                trans_payOrders.CommitTransaction(); //提交
                                return CommonLog.MsgSuccessInfo("收款成功");
                            }
                            catch (Exception ex)
                            {
                                GetMethodInfoAndWriteLogs(ex);
                                trans_payOrders.RollBackTransaction();//回滚
                                return CommonLog.MsgErrorInfo("收款失败,请重试");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,没任何订单");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 余额收款（1.更新订单支付状态为1已支付，2.更新客户余额） 12-10 (重中之重)
        /// </summary>
        /// <param name="stockOrdersParam"></param>
        /// <returns></returns>
        public string PayOrders(string payOrdersParam)
        {
            logParam = payOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(payOrdersParam);
            string tttagKey = CommonUrl.getURL(param, payOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderNewLS> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderNewLS>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            CustomerInfo _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", param.GetString("CustomerID"));
                            if (_customer != null)
                            {
                                for (int i = 0; i < OrderList.Count; i++)
                                {
                                    //未支付0
                                    if (OrderList[i].PaymentStatus == 0)
                                    {
                                        if (param.GetInt("Currency") == 1)
                                        {
                                            //客户当前余额大于当前订单应付金额（每个订单先四舍五入后再扣款10-11）
                                            if (_customer.Balance >= Math.Round(Convert.ToDecimal(OrderList[i].ConfirmPrice)) && _customer.Balance > 0) //Round 四舍六入五取偶
                                            {
                                                _customer.Balance = _customer.Balance + (-(Math.Round(Convert.ToDecimal(OrderList[i].ConfirmPrice))));//加减数
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("客户余额不足,请充值");
                                            }
                                        }
                                        else if (param.GetInt("Currency") == 2)
                                        {
                                            if (_customer.USDBalance >= Math.Round(Convert.ToDecimal(OrderList[i].ConfirmUSD)) && _customer.USDBalance > 0) //Round 四舍六入五取偶
                                            {
                                                _customer.USDBalance = _customer.USDBalance + (-(Math.Round(Convert.ToDecimal(OrderList[i].ConfirmUSD))));//加减数
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("客户余额不足,请充值");
                                            }
                                        }
                                        //更新客户余额
                                        #region
                                        int editBalanceResult = trans_payOrders.Edit(_customer);//更新客户余额事务 要用Edit 12-10
                                        //int editBalanceResult = trans_payOrders.Update("Customer.EditBalance", _customer);//更新客户余额事务 无法用Update
                                        if (editBalanceResult > 0)
                                        {
                                            //2.更新订单支付状态
                                            #region
                                            OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                            OrderList[i].PayTime = DateTime.Now;//支付时间
                                            OrderList[i].CurType = param.GetShort("Currency");//结算币种
                                            int editOrderResult = trans_payOrders.Edit(OrderList[i]);//更新订单支付状态
                                            if (editOrderResult > 0)
                                            {
                                                //继续
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("失败,更新订单支付状态失败,检查订单标识");
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("更新客户余额失败,检查客户标识");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        //已支付1订单
                                        return CommonLog.MsgErrorInfo("失败,订单已收款");
                                    }
                                }
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("客户不存在,检查客户标识");
                            }
                            try
                            {
                                //2.余额支付事务
                                trans_payOrders.CommitTransaction(); //提交事务
                                return CommonLog.MsgSuccessInfo("收款成功");
                            }
                            catch (Exception)
                            {
                                trans_payOrders.RollBackTransaction();//回滚事务
                                return CommonLog.MsgErrorInfo("收款失败");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,没任何订单");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 美金余额付款 2017-01-18
        /// </summary>
        /// <param name="payUSDOrdersParam"></param>
        /// <returns></returns>
        public string PayUSDOrders(string payUSDOrdersParam)
        {
            logParam = payUSDOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(payUSDOrdersParam);
            string tttagKey = CommonUrl.getURL(param, payUSDOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            CustomerInfo _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", param.GetString("CustomerID"));
                            if (_customer != null)
                            {
                                for (int i = 0; i < OrderList.Count; i++)
                                {
                                    //未支付0
                                    if (OrderList[i].PaymentStatus == 0)
                                    {
                                        //卖出美金$ 2017-01-18
                                        if (OrderList[i].ConfirmUSD != null)
                                        {
                                            //客户当前余额大于当前订单应付金额（每个订单先四舍五入后再扣款10-11）
                                            if (_customer.USDBalance >= Math.Round(Convert.ToDecimal(OrderList[i].ConfirmUSD)) && _customer.USDBalance > 0) //Round 四舍六入五取偶
                                            {
                                                // 1.更新客户余额
                                                #region
                                                _customer.USDBalance = _customer.USDBalance + (-(Math.Round(Convert.ToDecimal(OrderList[i].ConfirmUSD))));//加减数
                                                int editBalanceResult = trans_payOrders.Edit(_customer);//更新客户余额事务 要用Edit 12-10
                                                //int editBalanceResult = trans_payOrders.Update("Customer.EditBalance", _customer);//更新客户余额事务 无法用Update
                                                if (editBalanceResult > 0)
                                                {
                                                    //2.更新订单支付状态
                                                    #region
                                                    OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                    OrderList[i].PayTime = DateTime.Now;//支付时间
                                                    int editOrderResult = trans_payOrders.Edit(OrderList[i]);//更新订单支付状态
                                                    if (editOrderResult > 0)
                                                    {
                                                        //继续
                                                    }
                                                    else
                                                    {
                                                        //跳出
                                                        return CommonLog.MsgErrorInfo("失败,更新订单支付状态失败,检查订单标识");
                                                    }
                                                    #endregion
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,更新客户余额失败,检查客户标识");
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("失败,客户余额不足,请充值");
                                            }
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("失败,卖出$不存在");
                                        }
                                    }
                                    else
                                    {
                                        //已支付1订单
                                        return CommonLog.MsgErrorInfo("失败,订单已支付");
                                    }
                                }
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("失败,客户不存在,检查客户标识");
                            }
                            try
                            {
                                //2.余额支付事务
                                trans_payOrders.CommitTransaction(); //提交事务
                                return CommonLog.MsgSuccessInfo("余额支付成功");
                            }
                            catch (Exception)
                            {
                                trans_payOrders.RollBackTransaction();//回滚事务
                                return CommonLog.MsgErrorInfo("余额支付失败");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,没任何订单");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 取消到货 2017-02-20
        /// </summary>
        /// <param name="cancelArrivalOrdersParam"></param>
        /// <returns></returns>
        public string CancelArrivalOrders1(string cancelArrivalOrdersParam)
        {
            logParam = cancelArrivalOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(cancelArrivalOrdersParam);
            string tttagKey = CommonUrl.getURL(param, cancelArrivalOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_cancelArrivalOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderBy(t => t.OrderStatus).ToList();//从高到低排序 2待到货 3已到货 为了及时发现已到货的 //OrderByDescending降序 升序OrderBy
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? _totalPriceUSD = 0;//定货款,非现货,美金结算 12-24
                            decimal? _totalPriceRMB = 0;//定货款,非现货,人民币结算 2017-02-20
                            int? _count_USD = 0;//美金结算量
                            int? _count_RMB = 0;//人民币结算量
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                //统计条数和总货款
                                if (OrderList[i].Supplier.ToLower() != tttagKey)
                                {
                                    if (OrderList[i].CurType == 1)
                                    {
                                        _totalPriceRMB += OrderList[i].PurchaseRMB;//定货款(买入人民币)
                                        _count_RMB++;//定货条数
                                    }
                                    else if (OrderList[i].CurType == 2)
                                    {
                                        _totalPriceUSD += OrderList[i].PriceUSD;//定货款(买入美金)
                                        _count_USD++;//定货条数
                                    }
                                }
                                //更新订单
                                if (OrderList[i].OrderStatus == 3)
                                {
                                    OrderList[i].Arrival = 0;//入库(0 取消到货 1 确认到货)
                                    OrderList[i].ArrivalTime = null;//到货时间null
                                    OrderList[i].OrderStatus = 2;//待到货2
                                    OrderList[i].CurType = null;
                                    int editOrderStatusResult = trans_cancelArrivalOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                }
                                else
                                {
                                    return CommonLog.MsgErrorInfo("失败,订单待到货");
                                }
                            }
                            //RMB结算 2017-02-20
                            if (_count_RMB > 0)
                            {
                                //取消到货- 申请添加HK-$收入记录(一条)
                                #region
                                FlowInfo _flow = new FlowInfo();
                                //不同
                                _flow.Type = 1;//1收入 2 支出
                                //_flow.Account //申请时无需账户
                                _flow.Abstract = 7;//6确认到货 7 取消到货
                                _flow.Remarks = "取消到货" + _count_RMB + "条订单,应收入" + Math.Round(Convert.ToDecimal(_totalPriceRMB)) + "￥,请尽快审核";
                                //相同
                                _flow.Amount = _totalPriceRMB;//应收入RMB
                                _flow.Receivable = _totalPriceRMB;//应支出RMB
                                _flow.ApplyID = param.GetInt("ApplyID");
                                _flow.ArrivalTime = DateTime.Now;//操作时间
                                _flow.CreateTime = DateTime.Now;//申请时间
                                _flow.Status = 0;//0待审核
                                _flow.Currency = 1;//人民币1 美元2
                                _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                int addFlowResult = trans_cancelArrivalOrders.Add(_flow);//添加收入记录(1条)
                                if (addFlowResult > 0)
                                {
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                }
                                #endregion
                            }
                            //USD结算 2017-02-20                            
                            if (_count_USD > 0)
                            {
                                //判断BankID=7是虚拟账户还是真实账户 12-23
                                #region
                                BankInfo _bank = YZ.GetDatabase(tttagKey).Get<BankInfo>(7);//BankID = 7
                                if (_bank != null)
                                {
                                    //1相符0不相符
                                    if (_bank.CheckResult == 1)
                                    {
                                        //Type=1虚拟账户，财务不审核
                                        if (_bank.Type == 1)
                                        {
                                            //添加审核记录                                   
                                            //更新账户结余+收入
                                            #region
                                            _bank.BankBalance += _totalPriceUSD;//本次账户结余-支出
                                            _bank.UpdateTime = DateTime.Now;
                                            int editAccountBalanceResult = trans_cancelArrivalOrders.Edit(_bank);//更新账户结余 -只能用Edit
                                            if (editAccountBalanceResult > 0)
                                            {
                                                //取消到货- 添加HK-$收入已审核记录(一条)
                                                #region
                                                FlowInfo _flow = new FlowInfo();
                                                //不同
                                                _flow.Status = 1;//1已审核
                                                _flow.Type = 1;//1收入 2 支出
                                                _flow.Account = _bank.BankID;//7 HK-$账户
                                                _flow.Abstract = 7;//6确认到货 7 取消到货
                                                _flow.Purpose = 1;//1裸钻
                                                _flow.Remarks = "取消到货" + _count_USD + "条订单,采购账户收入" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$";
                                                _flow.UpdateTime = DateTime.Now;//审核时间
                                                _flow.Comments = "自动审核";
                                                _flow.Balance = _bank.BankBalance;//结余
                                                //相同
                                                _flow.Amount = _totalPriceUSD;//应收入USD
                                                _flow.Receivable = _totalPriceUSD;//应支出USD
                                                _flow.ApplyID = param.GetInt("ApplyID");
                                                _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                                _flow.ArrivalTime = DateTime.Now;//操作时间
                                                _flow.CreateTime = DateTime.Now;//申请时间
                                                _flow.Currency = _bank.Currency;//美元2 人民币1
                                                _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                int addFlowResult = trans_cancelArrivalOrders.Add(_flow);//添加收入记录(1条)
                                                if (addFlowResult > 0)
                                                {
                                                    //提交事务
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("更新账户结余失败");
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            //Type=0真实账户，财务审核
                                            //添加申请记录
                                            //取消到货- 申请添加HK-$收入记录(一条)
                                            #region
                                            FlowInfo _flow = new FlowInfo();
                                            //不同
                                            _flow.Type = 1;//1收入 2 支出
                                            _flow.Account = _bank.BankID;//7 HK-$账户
                                            _flow.Abstract = 7;//6确认到货 7 取消到货
                                            _flow.Remarks = "取消到货" + _count_USD + "条订单,采购账户收入" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$,请尽快审核";
                                            //相同
                                            _flow.Amount = _totalPriceUSD;//应收入USD
                                            _flow.Receivable = _totalPriceUSD;//应支出USD
                                            _flow.ApplyID = param.GetInt("ApplyID");
                                            _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                            _flow.ArrivalTime = DateTime.Now;//操作时间
                                            _flow.CreateTime = DateTime.Now;//申请时间
                                            _flow.Status = 0;//0待审核
                                            _flow.Currency = _bank.Currency;//美元2 人民币1
                                            _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                            int addFlowResult = trans_cancelArrivalOrders.Add(_flow);//添加收入记录(1条)
                                            if (addFlowResult > 0)
                                            {
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                            }
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,账户结余不相符,请对账相符后再确认/取消到货");
                                    }
                                }
                                else
                                {
                                    //账户不存在
                                    return CommonLog.MsgErrorInfo("失败,不存在虚拟账户");
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,订单标识不存在");
                        }
                        try
                        {
                            //3.取消到货事务
                            trans_cancelArrivalOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("取消到货成功");
                        }
                        catch (Exception)
                        {
                            trans_cancelArrivalOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("取消到货失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 确认到货 2017-02-21
        /// </summary>
        /// <param name="arrivalOrdersParam"></param>
        /// <returns></returns>
        public string ArrivalOrders1(string arrivalOrdersParam)
        {
            logParam = arrivalOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(arrivalOrdersParam);
            string tttagKey = CommonUrl.getURL(param, arrivalOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_arrivalOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderBy(t => t.OrderStatus).ToList();//从高到低排序 2待到货 3已到货 为了及时发现已支付的  //OrderByDescending降序 升序OrderBy
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            //更新订单采购汇率 2017-01-05
                            #region
                            //ExchangeInfo _exchange = YZ.GetDatabase(tttagKey).QueryForObject<ExchangeInfo>("Exchange.GetLastEx", null);
                            #endregion
                            decimal? _totalPriceUSD = 0;//定货款,非现货,美金结算 12-24
                            decimal? _totalPriceRMB = 0;//定货款,非现货,人民币结算 2017-02-20
                            int? _count = 0;//定货量
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                //统计条数和买入总价 非现货
                                #region
                                if (OrderList[i].Supplier.ToLower() != tttagKey)
                                {
                                    _count++;//定货条数
                                    if (param.GetShort("CurType") == 1)
                                    {
                                        if (OrderList[i].PurchaseRMB != null)
                                        {
                                            _totalPriceRMB += OrderList[i].PurchaseRMB;//定货款(买入人民币)
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("失败,请先核实买￥");
                                        }
                                    }
                                    else if (param.GetShort("CurType") == 2)
                                    {
                                        if (OrderList[i].PriceUSD != null)
                                        {
                                            _totalPriceUSD += OrderList[i].PriceUSD;//定货款(买入美金)
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("失败,请先核实买$");
                                        }
                                    }
                                }
                                #endregion
                                //更新订单
                                #region
                                if (OrderList[i].OrderStatus == 2)
                                {
                                    OrderList[i].Arrival = 1;//入库(0 取消到货 1 确认到货)
                                    OrderList[i].OrderStatus = 3;//3待出货
                                    OrderList[i].ArrivalTime = param.GetDataTime("ArrivalTime");//到货时间
                                    OrderList[i].CurType = param.GetShort("CurType");//到货结算币种 2017-02-20
                                    //有兑换记录
                                    //if (_exchange != null)
                                    //{
                                    //    OrderList[i].PurchaseExchangerate = _exchange.PurchaseExchange;//最新采购汇率 01-05
                                    //}
                                    int editOrderStatusResult = trans_arrivalOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                }
                                else
                                {
                                    //不匹配
                                    return CommonLog.MsgErrorInfo("失败,订单已到货");
                                }
                                #endregion
                            }
                            //存在定货订单时
                            if (_count > 0)
                            {
                                //结算币种 1人民币  2美金
                                if (param.GetInt("CurType") == 2)
                                {
                                    //美金结算
                                    //判断BankID=7是虚拟账户还是真实账户 12-23
                                    #region
                                    BankInfo _bank = YZ.GetDatabase(tttagKey).Get<BankInfo>(7);//BankID = 7
                                    if (_bank != null)
                                    {
                                        //1相符0不相符
                                        if (_bank.CheckResult == 1)
                                        {
                                            //Type=1虚拟账户，财务不审核
                                            if (_bank.Type == 1)
                                            {
                                                //添加审核记录                                            
                                                //确认到货- HK-$支出已审核记录(一条)
                                                #region
                                                _bank.BankBalance += -(_totalPriceUSD);//本次账户结余-支出
                                                //1-4
                                                if (_bank.BankBalance >= 0)
                                                {
                                                    _bank.UpdateTime = DateTime.Now;
                                                    int editAccountBalanceResult = trans_arrivalOrders.Edit(_bank);//更新账户结余 -只能用Edit
                                                    if (editAccountBalanceResult > 0)
                                                    {
                                                        //添加已审核支出记录
                                                        #region
                                                        FlowInfo _flow = new FlowInfo();
                                                        //不同
                                                        _flow.Status = 1;//1已审核
                                                        _flow.Type = 2;//1收入 2 支出
                                                        _flow.Account = _bank.BankID;//7 HK-$账户
                                                        _flow.Abstract = 6;//6确认到货 7 取消到货
                                                        _flow.Purpose = 1;//1裸钻
                                                        _flow.Remarks = "确认到货" + _count + "条订单,采购账户支出" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$";
                                                        _flow.UpdateTime = DateTime.Now;//审核时间
                                                        _flow.Comments = "自动审核";
                                                        _flow.Balance = _bank.BankBalance;//结余
                                                        //相同部分
                                                        _flow.Amount = _totalPriceUSD;//应支出USD 12-12
                                                        _flow.Receivable = _totalPriceUSD;//应支出USD
                                                        _flow.ApplyID = param.GetInt("ApplyID");
                                                        _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                                        _flow.ArrivalTime = DateTime.Now;//操作时间
                                                        _flow.CreateTime = DateTime.Now;//申请时间
                                                        _flow.Currency = _bank.Currency;//美元2 人民币1
                                                        _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                        int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                        if (addFlowResult > 0)
                                                        {
                                                            //提交事务
                                                        }
                                                        else
                                                        {
                                                            //跳出
                                                            return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                        }
                                                        #endregion
                                                    }
                                                    else
                                                    {
                                                        //跳出
                                                        return CommonLog.MsgErrorInfo("更新账户结余失败");
                                                    }
                                                    #endregion
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("到货失败,采购账户结余不足,请先入账");
                                                }
                                            }
                                            else
                                            {
                                                //Type=0真实账户，财务审核
                                                //添加申请记录
                                                //1.申请添加HK-$账户支出记录(一条)
                                                #region
                                                FlowInfo _flow = new FlowInfo();
                                                //不同
                                                _flow.Type = 2;//1收入 2 支出
                                                _flow.Account = _bank.BankID;//7 HK-$账户
                                                _flow.Abstract = 6;//6确认到货 7 取消到货
                                                _flow.Remarks = "确认到货" + _count + "条订单,采购账户支出" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$,请尽快审核";
                                                //相同部分
                                                _flow.Amount = _totalPriceUSD;//应支出USD 12-12
                                                _flow.Receivable = _totalPriceUSD;//应支出USD
                                                _flow.ApplyID = param.GetInt("ApplyID");
                                                //_flow.ArrivalTime = DateTime.Now;//操作时间
                                                _flow.CreateTime = DateTime.Now;//申请时间
                                                _flow.Status = 0;//0待审核
                                                _flow.Currency = _bank.Currency;//美元2 人民币1
                                                _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                if (addFlowResult > 0)
                                                {
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                }
                                                #endregion
                                            }
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("失败,账户结余不相符,请对账相符后再确认/取消到货");
                                        }
                                    }
                                    else
                                    {
                                        //账户不存在
                                        return CommonLog.MsgErrorInfo("失败,不存在虚拟账户");
                                    }
                                    #endregion
                                }
                                else if (param.GetInt("CurType") == 1)
                                {
                                    //RMB结算 2017-02-20
                                    //添加申请记录
                                    #region
                                    FlowInfo _flow = new FlowInfo();
                                    //不同
                                    _flow.Type = 2;//1收入 2 支出
                                    //_flow.Account //申请时无需账户
                                    _flow.Abstract = 6;//6确认到货 7 取消到货
                                    _flow.Remarks = "确认到货" + _count + "条订单,应支出" + Math.Round(Convert.ToDecimal(_totalPriceRMB)) + "￥,请尽快审核";
                                    //相同部分
                                    _flow.Amount = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应支出RMB
                                    _flow.Receivable = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应支出RMB
                                    _flow.ApplyID = param.GetInt("ApplyID");
                                    //_flow.ArrivalTime = DateTime.Now;//到账时间
                                    _flow.CreateTime = DateTime.Now;//申请时间
                                    _flow.Status = 0;//0待审核
                                    _flow.Currency = param.GetShort("CurType");//人民币1 美元2
                                    _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                    int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                    if (addFlowResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                    }
                                    #endregion
                                }
                            }
                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("失败,订单标识不存在");
                        }
                        try
                        {
                            //3.到货事务
                            trans_arrivalOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("到货成功");
                        }
                        catch (Exception)
                        {
                            trans_arrivalOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("到货失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 订单确认到货-取消到货（A.确认到货：1.更新订单状态为3待出货，2.从HK-美金账户支出取货款$ ; B.取消到货 : 1.更新订单状态为2待到货，2.HK-美金账户收入取货款$） 12-9 (重中之重)
        /// </summary>
        /// <param name="arrivalOrdersParam"></param>
        /// <returns></returns>
        public string ArrivalOrders2(string arrivalOrdersParam)
        {
            logParam = arrivalOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(arrivalOrdersParam);
            string tttagKey = CommonUrl.getURL(param, arrivalOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_arrivalOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderBy(t => t.OrderStatus).ToList();//从高到低排序 2待到货 3已到货 为了及时发现已支付的  //OrderByDescending降序 升序OrderBy
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            //更新订单采购汇率 2017-01-05
                            #region
                            //ExchangeInfo _exchange = YZ.GetDatabase(tttagKey).QueryForObject<ExchangeInfo>("Exchange.GetLastEx", null);
                            #endregion
                            decimal? _totalPriceUSD = 0;//定货款,非现货,美金结算 12-24
                            decimal? _totalPriceRMB = 0;//定货款,非现货,人民币结算 2017-02-20
                            int? _count = 0;//定货量
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                //非现货
                                if (OrderList[i].Supplier.ToLower() != tttagKey)
                                {
                                    _totalPriceUSD += OrderList[i].PriceUSD;//定货款(买入美金)
                                    if (param.GetShort("CurType") == 1)
                                    {
                                        if (OrderList[i].PurchaseRMB != null)
                                        {
                                            //人工录入
                                            _totalPriceRMB += OrderList[i].PurchaseRMB;//定货款(买入人民币)
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("失败,请先核实买￥");
                                        }
                                    }
                                    _count++;//定货条数
                                }
                                if (OrderList[i].OrderStatus != 3 && param.GetInt("Arrival") == 1)
                                {
                                    //确认到货Arrival=1
                                    #region
                                    OrderList[i].Arrival = param.GetInt("Arrival");//入库(0 取消到货 1 确认到货)
                                    OrderList[i].OrderStatus = 3;//3待出货
                                    OrderList[i].ArrivalTime = param.GetDataTime("ArrivalTime");//到货时间
                                    OrderList[i].CurType = param.GetShort("CurType");//到货结算币种 2017-02-20
                                    //有兑换记录
                                    //if (_exchange != null)
                                    //{
                                    //    OrderList[i].PurchaseExchangerate = _exchange.PurchaseExchange;//最新采购汇率 01-05
                                    //}
                                    int editOrderStatusResult = trans_arrivalOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                    #endregion
                                }
                                else if (OrderList[i].OrderStatus != 2 && param.GetInt("Arrival") == 0)
                                {
                                    //取消到货 Arrival=0
                                    #region
                                    OrderList[i].Arrival = param.GetInt("Arrival");//入库(0 取消到货 1 确认到货)
                                    OrderList[i].OrderStatus = 2;//待到货2
                                    OrderList[i].ArrivalTime = param.GetDataTime("ArrivalTime");//到货时间null
                                    OrderList[i].CurType = null;//初始值 2017-02-20
                                    int editOrderStatusResult = trans_arrivalOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //不匹配
                                    return CommonLog.MsgErrorInfo("失败,订单已到货 或 未到货");
                                }
                            }
                            //结算币种 1人民币  2美金
                            if (param.GetInt("CurType") == 2)
                            {
                                //美金结算
                                //判断BankID=7是虚拟账户还是真实账户 12-23
                                #region
                                BankInfo _bank = YZ.GetDatabase(tttagKey).Get<BankInfo>(7);//BankID = 7
                                if (_bank != null)
                                {
                                    //1相符0不相符
                                    if (_bank.CheckResult == 1)
                                    {
                                        //Type=1虚拟账户，财务不审核
                                        if (_bank.Type == 1)
                                        {
                                            //添加审核记录
                                            #region
                                            //确认到货- HK-$支出已审核记录(一条)
                                            if (param.GetInt("Arrival") == 1)
                                            {
                                                //更新账户结余-支出
                                                #region
                                                _bank.BankBalance += -(_totalPriceUSD);//本次账户结余-支出
                                                //1-4
                                                if (_bank.BankBalance >= 0)
                                                {
                                                    _bank.UpdateTime = DateTime.Now;
                                                    int editAccountBalanceResult = trans_arrivalOrders.Edit(_bank);//更新账户结余 -只能用Edit
                                                    if (editAccountBalanceResult > 0)
                                                    {
                                                        //添加已审核支出记录
                                                        #region
                                                        FlowInfo _flow = new FlowInfo();
                                                        //不同
                                                        _flow.Status = 1;//1已审核
                                                        _flow.Type = 2;//1收入 2 支出
                                                        _flow.Account = _bank.BankID;//7 HK-$账户
                                                        _flow.Abstract = 6;//6确认到货 7 取消到货
                                                        _flow.Purpose = 1;//1裸钻
                                                        _flow.Remarks = "确认到货" + _count + "条订单,采购账户支出" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$";
                                                        _flow.UpdateTime = DateTime.Now;//审核时间
                                                        _flow.Comments = "自动审核";
                                                        _flow.Balance = _bank.BankBalance;//结余
                                                        //相同部分
                                                        _flow.Amount = _totalPriceUSD;//应支出USD 12-12
                                                        _flow.Receivable = _totalPriceUSD;//应支出USD
                                                        _flow.ApplyID = param.GetInt("ApplyID");
                                                        _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                                        _flow.ArrivalTime = DateTime.Now;//操作时间
                                                        _flow.CreateTime = DateTime.Now;//申请时间
                                                        _flow.Currency = _bank.Currency;//美元2 人民币1
                                                        _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                        int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                        if (addFlowResult > 0)
                                                        {
                                                            //提交事务
                                                        }
                                                        else
                                                        {
                                                            //跳出
                                                            return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                        }
                                                        #endregion
                                                    }
                                                    else
                                                    {
                                                        //跳出
                                                        return CommonLog.MsgErrorInfo("更新账户结余失败");
                                                    }
                                                    #endregion
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("到货失败,采购账户结余不足,请先入账");
                                                }
                                            }
                                            else
                                            {
                                                //更新账户结余+收入
                                                #region
                                                _bank.BankBalance += _totalPriceUSD;//本次账户结余-支出
                                                _bank.UpdateTime = DateTime.Now;
                                                int editAccountBalanceResult = trans_arrivalOrders.Edit(_bank);//更新账户结余 -只能用Edit
                                                if (editAccountBalanceResult > 0)
                                                {
                                                    //取消到货- 添加HK-$收入已审核记录(一条)
                                                    #region
                                                    FlowInfo _flow = new FlowInfo();
                                                    //不同
                                                    _flow.Status = 1;//1已审核
                                                    _flow.Type = 1;//1收入 2 支出
                                                    _flow.Account = _bank.BankID;//7 HK-$账户
                                                    _flow.Abstract = 7;//6确认到货 7 取消到货
                                                    _flow.Purpose = 1;//1裸钻
                                                    _flow.Remarks = "取消到货" + _count + "条订单,采购账户收入" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$";
                                                    _flow.UpdateTime = DateTime.Now;//审核时间
                                                    _flow.Comments = "自动审核";
                                                    _flow.Balance = _bank.BankBalance;//结余
                                                    //相同
                                                    _flow.Amount = _totalPriceUSD;//应收入USD
                                                    _flow.Receivable = _totalPriceUSD;//应支出USD
                                                    _flow.ApplyID = param.GetInt("ApplyID");
                                                    _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                                    _flow.ArrivalTime = DateTime.Now;//操作时间
                                                    _flow.CreateTime = DateTime.Now;//申请时间
                                                    _flow.Currency = _bank.Currency;//美元2 人民币1
                                                    _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                    int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                    if (addFlowResult > 0)
                                                    {
                                                        //提交事务
                                                    }
                                                    else
                                                    {
                                                        //跳出
                                                        return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                    }
                                                    #endregion
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("更新账户结余失败");
                                                }
                                                #endregion
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            //Type=0真实账户，财务审核
                                            //添加申请记录
                                            #region
                                            //确认到货- HK-$支出
                                            if (param.GetInt("Arrival") == 1)
                                            {
                                                //1.申请添加HK-$账户支出记录(一条)
                                                #region
                                                FlowInfo _flow = new FlowInfo();
                                                //不同
                                                _flow.Type = 2;//1收入 2 支出
                                                _flow.Account = _bank.BankID;//7 HK-$账户
                                                _flow.Abstract = 6;//6确认到货 7 取消到货
                                                _flow.Remarks = "确认到货" + _count + "条订单,采购账户支出" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$,请尽快审核";
                                                //相同部分
                                                _flow.Amount = _totalPriceUSD;//应支出USD 12-12
                                                _flow.Receivable = _totalPriceUSD;//应支出USD
                                                _flow.ApplyID = param.GetInt("ApplyID");
                                                _flow.ArrivalTime = DateTime.Now;//操作时间
                                                _flow.CreateTime = DateTime.Now;//申请时间
                                                _flow.Status = 0;//0待审核
                                                _flow.Currency = _bank.Currency;//美元2 人民币1
                                                _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                if (addFlowResult > 0)
                                                {
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                //取消到货- 申请添加HK-$收入记录(一条)
                                                #region
                                                FlowInfo _flow = new FlowInfo();
                                                //不同
                                                _flow.Type = 1;//1收入 2 支出
                                                _flow.Account = _bank.BankID;//7 HK-$账户
                                                _flow.Abstract = 7;//6确认到货 7 取消到货
                                                _flow.Remarks = "取消到货" + _count + "条订单,采购账户收入" + Math.Round(Convert.ToDecimal(_totalPriceUSD)) + "$,请尽快审核";
                                                //相同
                                                _flow.Amount = _totalPriceUSD;//应收入USD
                                                _flow.Receivable = _totalPriceUSD;//应支出USD
                                                _flow.ApplyID = param.GetInt("ApplyID");
                                                _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                                _flow.ArrivalTime = DateTime.Now;//操作时间
                                                _flow.CreateTime = DateTime.Now;//申请时间
                                                _flow.Status = 0;//0待审核
                                                _flow.Currency = _bank.Currency;//美元2 人民币1
                                                _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                                int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                                if (addFlowResult > 0)
                                                {
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                                }
                                                #endregion
                                            }
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,账户结余不相符,请对账相符后再确认/取消到货");
                                    }
                                }
                                else
                                {
                                    //账户不存在
                                    return CommonLog.MsgErrorInfo("失败,不存在虚拟账户");
                                }
                                #endregion
                            }
                            else if (param.GetInt("CurType") == 1)
                            {
                                //RMB结算 2017-02-20
                                //添加申请记录
                                #region
                                //确认到货
                                if (param.GetInt("Arrival") == 1)
                                {
                                    //1.申请添加支出记录(一条)
                                    #region
                                    FlowInfo _flow = new FlowInfo();
                                    //不同
                                    _flow.Type = 2;//1收入 2 支出
                                    //_flow.Account //申请时无需账户
                                    _flow.Abstract = 6;//6确认到货 7 取消到货
                                    _flow.Remarks = "确认到货" + _count + "条订单,应支出" + Math.Round(Convert.ToDecimal(_totalPriceRMB)) + "￥,请尽快审核";
                                    //相同部分
                                    _flow.Amount = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应支出RMB
                                    _flow.Receivable = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应支出RMB
                                    _flow.ApplyID = param.GetInt("ApplyID");
                                    _flow.ArrivalTime = DateTime.Now;//操作时间
                                    _flow.CreateTime = DateTime.Now;//申请时间
                                    _flow.Status = 0;//0待审核
                                    _flow.Currency = param.GetShort("CurType");//人民币1 美元2
                                    _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                    int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                    if (addFlowResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //取消到货- 申请添加HK-$收入记录(一条)
                                    #region
                                    FlowInfo _flow = new FlowInfo();
                                    //不同
                                    _flow.Type = 1;//1收入 2 支出
                                    //_flow.Account //申请时无需账户
                                    _flow.Abstract = 7;//6确认到货 7 取消到货
                                    _flow.Remarks = "取消到货" + _count + "条订单,应收入" + Math.Round(Convert.ToDecimal(_totalPriceRMB)) + "￥,请尽快审核";
                                    //相同
                                    _flow.Amount = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应收入RMB
                                    _flow.Receivable = Math.Round(Convert.ToDecimal(_totalPriceRMB));//应支出RMB
                                    _flow.ApplyID = param.GetInt("ApplyID");
                                    _flow.ReviewID = param.GetInt("ApplyID");//01-11
                                    _flow.ArrivalTime = DateTime.Now;//操作时间
                                    _flow.CreateTime = DateTime.Now;//申请时间
                                    _flow.Status = 0;//0待审核
                                    _flow.Currency = param.GetShort("CurType");//人民币1 美元2
                                    _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                    int addFlowResult = trans_arrivalOrders.Add(_flow);//添加收入记录(1条)
                                    if (addFlowResult > 0)
                                    {
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查流水标识");
                                    }
                                    #endregion
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("失败,订单标识不存在");
                        }
                        try
                        {
                            //3.到货事务
                            trans_arrivalOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("到货成功");
                        }
                        catch (Exception)
                        {
                            trans_arrivalOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("到货失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 订单自留（1.更新订单状态为6已自留，2.将客户已支付￥退还到客户余额，3.回裸钻库存） 12-9 (重中之重)
        /// </summary>
        /// <param name="stockOrdersParam"></param>
        /// <returns></returns>
        public string StockOrders2(string stockOrdersParam)
        {
            logParam = stockOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(stockOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, stockOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_stockOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? _confirmPrice = 0;//已支付款
                            int? _count = 0;//个数
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                if (OrderList[i].OrderStatus != 6)
                                {
                                    //1已支付
                                    if (OrderList[i].PaymentStatus == 1)
                                    {
                                        _confirmPrice += OrderList[i].ConfirmPrice;
                                        _count++;
                                    }
                                    OrderList[i].OrderStatus = 6;//6已自留
                                    OrderList[i].SalesRemarks = param.GetString("SalesRemarks").Replace(" ", "");//作废备注
                                    int editOrderStatusResult = trans_stockOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续                                        
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                }
                                else
                                {
                                    //已自留6
                                    return CommonLog.MsgErrorInfo("失败,订单已自留");
                                }
                            }
                            //1.如果订单已支付，将已支付RMB存入客户的余额
                            #region
                            CustomerInfo _customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.GetInt("CustomerID"));
                            if (_customer != null)
                            {
                                _customer.Balance += _confirmPrice.Value;//卖出￥
                                int editBalanceResult = trans_stockOrders.Edit(_customer);//更新客户帐号余额 -只能用Edit
                                if (editBalanceResult > 0)
                                {
                                    //添加客户余额变动记录 12-28
                                    FlowInfo _flow = new FlowInfo();
                                    _flow.CustomerBalance = _customer.Balance;//12-28
                                    _flow.ApplyID = param.GetInt("SalesUserID");
                                    _flow.ReviewID = param.GetInt("SalesUserID");
                                    _flow.CustomerID = _customer.CustomerID;
                                    _flow.Amount = _confirmPrice;//01-11
                                    _flow.CreateTime = DateTime.Now;
                                    _flow.UpdateTime = DateTime.Now;
                                    _flow.Remarks = "已自留" + OrderList.Count + "条订单,其中已支付" + _count + "条,自动退还" + _confirmPrice + "到客户余额";
                                    _flow.Comments = "自动审核";
                                    _flow.OrderIDs = param.GetString("OrderIDs");
                                    _flow.Abstract = 4;//自留变现
                                    _flow.Purpose = 1;//1裸钻
                                    _flow.Status = 1;//已审核
                                    int addFlowResult = trans_stockOrders.Add(_flow);//更新收入记录
                                    if (addFlowResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("添加记录失败");
                                    }
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("失败,检查客户标识");
                                }
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("失败,检查客户标识");
                            }
                            #endregion
                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("失败,订单标识不存在");
                        }
                        try
                        {
                            //2.自留变现货事务
                            trans_stockOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("自留成功");
                        }
                        catch (Exception)
                        {
                            trans_stockOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("自留失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }


        /// <summary>
        /// 订单退回（1.更新订单状态为7已退回，2.收回取货款$到HK-美金账户(真实账户、虚拟账户Type=1)，3.将客户已支付￥退还到客户余额） 12-9     （重中之重）
        /// </summary>
        /// <param name="returnOrdersParam"></param>
        /// <returns></returns>
        public string ReturnOrders2(string returnOrdersParam)
        {
            logParam = returnOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(returnOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, returnOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_returnOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? _priceUSD = 0;//定货款,非现货 12-28
                            decimal? _confirmPrice = 0;//已支付款
                            int? _count = 0;//已支付个数
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                if (OrderList[i].OrderStatus != 7)
                                {
                                    //非现货
                                    if (OrderList[i].Supplier.ToLower() != tttagKey)
                                    {
                                        _priceUSD += OrderList[i].PriceUSD;//定货款(买入美金)
                                    }
                                    if (OrderList[i].PaymentStatus == 1)
                                    {
                                        _confirmPrice += OrderList[i].ConfirmPrice;
                                        _count++;
                                    }
                                    OrderList[i].OrderStatus = 7;//7已退回
                                    //退回供应商 2017-2-23 周总取货款计算是按照到货时间ArrivalTime和CurType=2的 所以退回的必须回位
                                    OrderList[i].Arrival = 0;
                                    OrderList[i].ArrivalTime = null;
                                    OrderList[i].SalesRemarks = param.GetString("SalesRemarks").Replace(" ", "");//作废备注
                                    int editOrderStatusResult = trans_returnOrders.Edit(OrderList[i]);//更新订单事务
                                    if (editOrderStatusResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                    }
                                }
                                else
                                {
                                    //已退回7
                                    return CommonLog.MsgErrorInfo("失败,订单已退回");
                                }
                            }
                            //1.添加一条HK-$账户收入记录
                            #region
                            FlowInfo _flow = new FlowInfo();
                            //判断7账户Type
                            BankInfo _bank = YZ.GetDatabase(tttagKey).Get<BankInfo>(7);//BankID = 7
                            if (_bank != null)
                            {
                                //虚拟账户 - 自动审核
                                if (_bank.Type == 1)
                                {
                                    //更新银行账户余额
                                    #region
                                    _bank.BankBalance += _priceUSD;//本次账户结余+收入
                                    _bank.UpdateTime = DateTime.Now;
                                    int editAccountBalanceResult = trans_returnOrders.Edit(_bank);//更新账户结余 -只能用Edit
                                    if (editAccountBalanceResult > 0)
                                    {
                                        //虚拟账户-无需审核
                                        _flow.Type = 1;//1收入 2 支出
                                        _flow.Amount = _priceUSD;//应收入USD
                                        _flow.Receivable = _priceUSD;//应收入USD
                                        _flow.Account = 7;//7 HK-$账户
                                        _flow.ApplyID = param.GetInt("SalesUserID");//申请人ID
                                        _flow.ReviewID = param.GetInt("SalesUserID");//审核人ID
                                        _flow.CustomerID = param.GetInt("CustomerID");//客户ID 同一客户
                                        _flow.ArrivalTime = DateTime.Now;//操作时间
                                        _flow.CreateTime = DateTime.Now;//申请时间
                                        _flow.Abstract = 3;//操作类型（摘要）3退回
                                        _flow.Purpose = 1;//1裸钻
                                        _flow.Currency = _bank.Currency;//币种 2美元
                                        _flow.Remarks = "已退回" + OrderList.Count + "条订单,采购账户应收" + _priceUSD + "$";
                                        _flow.Comments = "自动审核";
                                        _flow.UpdateTime = DateTime.Now;
                                        _flow.Balance = _bank.BankBalance;//账户结余 12-28
                                        _flow.Status = 1;//1已审核
                                        _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,更新账户结余失败");
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //真实账户-人工审核
                                    _flow.Type = 1;//1收入 2 支出
                                    _flow.Amount = _priceUSD;//应收入USD
                                    _flow.Receivable = _priceUSD;//应收入USD
                                    _flow.Account = 7;//7 HK-$账户
                                    _flow.ApplyID = param.GetInt("SalesUserID");//申请人ID
                                    _flow.CustomerID = param.GetInt("CustomerID");//客户ID 同一客户
                                    _flow.ArrivalTime = DateTime.Now;//操作时间
                                    _flow.CreateTime = DateTime.Now;//申请时间
                                    _flow.Abstract = 3;//操作类型（摘要）3退回
                                    _flow.Currency = _bank.Currency;//币种 2美元
                                    _flow.Remarks = "已退回" + OrderList.Count + "条订单,采购账户应收" + _priceUSD + "$,请尽快审核";
                                    _flow.Status = 0;//0待审核
                                    _flow.OrderIDs = param.GetString("OrderIDs");//订单
                                }
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("失败,账户7不存在");
                            }
                            int addFlowResult = trans_returnOrders.Add(_flow);//添加收入记录
                            if (addFlowResult > 0)
                            {
                                CustomerInfo _customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(_flow.CustomerID);//同一客户
                                //2.如果订单已支付，将已支付RMB存入客户的余额
                                #region
                                if (_customer != null)
                                {
                                    _customer.Balance += _confirmPrice.Value;//卖出￥
                                    int editBalanceResult = trans_returnOrders.Edit(_customer);//更新客户帐号余额 -只能用Edit
                                    if (editBalanceResult > 0)
                                    {
                                        //添加客户余额变动记录
                                        _flow.CustomerBalance = _customer.Balance;//12-28
                                        _flow.Remarks += ";" + "其中" + _count + "条已支付,自动退还" + _confirmPrice.Value + "到客户余额";
                                        int editFlowResult = trans_returnOrders.Edit(_flow);//更新收入记录
                                        if (editFlowResult > 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("失败,更新客户余额失败");
                                        }
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,检查客户标识");
                                    }
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("失败,检查客户标识");
                                }
                                #endregion
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("失败,检查流水标识");
                            }
                            #endregion
                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("失败,订单标识不存在");
                        }
                        try
                        {
                            //3.退回供应商事务
                            trans_returnOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("退回成功");
                        }
                        catch (Exception)
                        {
                            trans_returnOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("退回失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }
        /// <summary>
        /// 提交订单  --含事务 ***************************************过时*****************************************
        /// </summary>
        /// <param name="submmitOrderParam"></param>
        /// <returns></returns>
        public string SubmitOrder(string submmitOrderParam)
        {
            logParam = submmitOrderParam;
            HashParam param = Json.Deserialize<HashParam>(submmitOrderParam);
            string tttagKey = CommonUrl.getURL(param, submmitOrderParam); 
            StringBuilder tempSns = new StringBuilder();
            int addOrderResult = 0;//生成订单结果
            int removeFromCartResult = 0;//移除购物车结果
            TransmissionOrderResult submitOrderResult1 = new TransmissionOrderResult();
            try
            {
                //CustomerInfo _customerInf = null;
                //Console.WriteLine(_customerInf);
                //return
                //先将字符转字符数组，然后将字符数组转整形数组
                #region
                //string[] _inventoryIDs = param.GetString("InventoryIDs").TrimEnd(',').Split(',');//标准111,222,333,444 (兼容111,222,333,444,) 
                //int[] InventoryIDs = Array.ConvertAll<string, int>(_inventoryIDs, s => Convert.ToInt32(s)); //string[] 转成int[]
                var failCount = 0;
                var successCount = 0;
                var failCount1 = 0;
                var successCount1 = 0;
                #endregion
                //用来操作移除非现货供应商的货
                List<int> list = param.GetString("InventoryIDs").TrimEnd(',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();// new System.Collections.ArrayList(InventoryIDs);
                int[] cartIds = list.ToArray();//这个是用来批量删除购物车的id
                if (param.GetString("CustomerID") == "undefined" || param.GetString("CustomerID") == "")
                { //客户登录信息消失或失效
                    return CommonLog.MsgErrorInfo("客户登录失效");//CustomerID一定要存在
                }
                CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.GetInt("CustomerID"));
                if (_customerInfo == null)
                {
                    return CommonLog.MsgErrorInfo("客户标识不存在");//CustomerID一定要存在
                }
                else
                {
                    #region
                    var iParam = new
                    {
                        ID = list.ToArray(),
                        CustomerID = _customerInfo.CustomerID,
                        IsFancy = param.GetString("IsFancy") == "" ? "0" : param.GetString("IsFancy")
                    };
                    var inventoryJson = GetInventoryInfos(JsonConvert.SerializeObject(iParam));
                    var inventoryData = new { data = new object() };
                    var anonymousData = JsonConvert.DeserializeAnonymousType(inventoryJson, inventoryData);
                    // TransmissionOrderResult getOrderResult = PublicInterface.OprationOrders(InventoryIDs, "get");//OprationOrders 没有成功调用的话 不会提交
                    if (inventoryJson != "")
                    {
                        //var responseJson = MyHttpRequest.ConvertToInventoryFormat(inventoryJson); //转化成库存的Json格式
                        PageList<InventoryInfoResult> _SoldInventoryInfos = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(JsonConvert.SerializeObject(anonymousData.data));//转成PageList
                        if (_SoldInventoryInfos != null && _SoldInventoryInfos.Data.Count > 0)
                        {
                            SystemSetting setting = new SystemSetting();
                            #region
                            foreach (var item in _SoldInventoryInfos.Data)
                            {
                                if (item.Supplier.ToLower() != tttagKey)
                                {
                                    list.RemoveAt(list.IndexOf(Convert.ToInt32(item.ID)));
                                }
                                //DiamondsPriceHandler.ComputePrice(item, _customerInfo, setting); 库存查询时已计算
                            }
                            #endregion
                            //有至少一个成功下单，将有两大事务：生成本地订单和移除购物车
                            #region
                            //单个订单生成成功
                            for (int j = 0; j < _SoldInventoryInfos.Data.Count; j++)
                            {
                                //单粒库存
                                InventoryInfoResult _inventoryInfo = (InventoryInfoResult)_SoldInventoryInfos.Data[j];//必须是InventoryInfoResult类型                                           
                                var orderParam = new OrderInfo() { InventoryID = (int)_inventoryInfo.ID, CustomerID = param.GetInt("CustomerID") };
                                OrderInfo orderInfo = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.SelectOrderByInventoryID", orderParam);
                                if (orderInfo == null)  //防止重复正常的订单 12345为正常的订单
                                {
                                    if (_inventoryInfo != null)
                                    {
                                        //赋值
                                        #region
                                        OrderInfo _order = new OrderInfo();
                                        _order.CreateTime = DateTime.Now;//下单时间
                                        //现货供应商(不区分大小写)
                                        if (_inventoryInfo.Supplier.ToLower() == tttagKey)
                                        {
                                            //现货
                                            _order.OrderStatus = 3;//订单状态 3（待出货）
                                            _order.DeliveryTime = DateTime.Now;//发货时间 2017-02-10
                                            _order.ArrivalTime = DateTime.Now;//到货时间
                                            _order.Arrival = 1;//已到货
                                        }
                                        else
                                        {
                                            //定货
                                            _order.OrderStatus = 1;//订单状态 1（下单成功，采购中）
                                        }
                                        _order.PaymentStatus = 0;//收款状态 0 （未付款）
                                        //_order.ReceiptStatus = 0;//付款状态
                                        _order.CustomerID = param.GetInt("CustomerID") ?? 0;  //客户ID
                                        _order.PurchaseUserID = _customerInfo.PurchaseUserID ?? 0;//采购ID  防止客户帐号未分配业务和采购时下单，导致订单列表加载报错

                                        _order.InventoryID = _inventoryInfo.ID;//库存ID 
                                        if (!string.IsNullOrEmpty(_inventoryInfo.SecondSN))
                                        {
                                            _order.Supplier = _inventoryInfo.SecondSN;//供应商
                                        }
                                        else
                                        {
                                            _order.Supplier = _inventoryInfo.Supplier;//供应商
                                        }
                                        _order.Rapnet = _inventoryInfo.Rapnet;//国际报价（数据中心订单Rapnet始终为null） 
                                        _order.Remarks = param.GetString("Remarks").Replace(" ", ""); //客户下单备注 (去除空格 255长度)
                                        _order.Confirmdiscount = _inventoryInfo.DiscountReturn;//卖出退点
                                        //买入价格
                                        _order.DiscountReturn = _inventoryInfo.SourceDiscountReturn;//买入退点
                                        _order.PriceUSD = _inventoryInfo.SourceDolarPerGrain.Value;//买入美金总价
                                        //卖出价格
                                        //_order.Confirmdiscount = _inventoryInfo.CustomerDiscountReturn;//卖出退点
                                        //_order.ConfirmPrice = _inventoryInfo.CustomerRMBPerGrain;//卖出人民币总价
                                        ////_order.ConfirmUSD = _inventoryInfo.CustomerRMBPerGrain / setting.GetRate();//卖出美金 = 卖出人民币总价 / 销售汇率 01-11
                                        //_order.ConfirmUSD = _inventoryInfo.CustomerDolarPerGrain;//卖出美金 = 客户美金总价 2017-01-19

                                        _order.ConfirmPrice = _inventoryInfo.RMBPerGrain.Value;//卖出人民币总价
                                        //_order.ConfirmUSD = _inventoryInfo.CustomerRMBPerGrain / setting.GetRate();//卖出美金 = 卖出人民币总价 / 销售汇率 01-11
                                        _order.ConfirmUSD = _inventoryInfo.USDPerGrain;//卖出美金 = 客户美金总价 2017-01-19
                                        //两大汇率
                                        _order.SalesExchangerate = setting.GetRate();//销售汇率
                                        _order.PurchaseExchangerate = setting.GetPurchaseExchangeRate();//采购汇率
                                        //_order.PurchaseRMB = _inventoryInfo.PurchaseRMB.Value; //_inventoryInfo.SourceDolarPerGrain * _order.SalesExchangerate;
                                        //已付未付状态
                                        _order.ReceiptStatus = _inventoryInfo.ReceiptStatus;
                                        #endregion
                                        using (ITransaction trans_addOrder = YZ.GetTransaction(tttagKey))
                                        {
                                            //执行
                                            #region
                                            try
                                            {
                                                addOrderResult = trans_addOrder.Add(_order);//生成单条订单 
                                                //单条订单生成成功,就移除购物车。
                                                if (addOrderResult > 0)
                                                {
                                                    if (j == 0)  //加入1个sn
                                                        tempSns.Append(_inventoryInfo.SN);

                                                    try
                                                    {
                                                        if (j == 0) //因为是批量，所以第一次删除即可
                                                        {
                                                            DelCartInfo(_order.GoodsTypeID, param.GetInt("CustomerID").Value, cartIds, tttagKey);
                                                        }
                                                        //立即购买 流程
                                                        try
                                                        {
                                                            trans_addOrder.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                                                            successCount++;
                                                        }
                                                        catch (Exception exc)
                                                        {
                                                            GetMethodInfoAndWriteLogs(exc);
                                                            trans_addOrder.RollBackTransaction();//回滚事务
                                                            failCount++;
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        failCount++;
                                                        GetMethodInfoAndWriteLogs(ex);
                                                        return CommonLog.MsgErrorInfo("移除购物车：程序错误：");
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                failCount++;
                                                GetMethodInfoAndWriteLogs(ex);
                                                return CommonLog.MsgErrorInfo("生成订单，程序错误");
                                            }
                                            #endregion
                                        }
                                    }
                                }
                                else
                                {
                                    failCount++;
                                }
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("获取信息失败，请重试");
                    }
                    #endregion
                    ////调用一级订单提交接口  下单 不走数据中心
                    if (tttagKey.Contains("__"))
                    {
                        param["TagKey"] = tttagKey.Split(new string[] { "__" }, StringSplitOptions.None)[0]; //上一级需要加上一级自己的key
                        var token = param.GetString("ParentKey");
                        param.Remove("ParentKey");
                        param.Remove("CustomerID"); //移除二级本身的客户ID
                        var responseJson = SubmitOrderByYiJi(JsonConvert.SerializeObject(param), token).Result;
                    }
                    else
                    {
                        #region
                        if (list.Count > 0) //还有现货，则提交
                        {
                            try
                            {
                                TransmissionOrderResult submitOrderResult = AllPublic.OprationOrders(list.ToArray(), "add", tttagKey);//提交订单 InventoryID  (OprationOrders 包含了提交订单、删除订单 和获取订单)
                                if (submitOrderResult != null && submitOrderResult.Successful != null && submitOrderResult.Failed != null)
                                {
                                    successCount1 = submitOrderResult.Successful.Length;
                                    failCount1 = submitOrderResult.Failed.Length;
                                }
                                else
                                {
                                    successCount1 = -1;
                                    failCount1 = -1;
                                }
                            }
                            catch (Exception ex)
                            {
                                GetMethodInfoAndWriteLogs(ex);
                                Logger.Error(typeof(Retail), "SubmitOrder:7300");
                                successCount1 = -1;
                                failCount1 = -1;
                                throw;
                            }
                        }
                    }
                    #endregion
                    var msg = new
                    {
                        Successful = successCount,
                        Successful1 = successCount1,
                        Failed = failCount,
                        Failed1 = failCount1,
                    };
                    if (successCount > 0)//成功则发送短信
                    {
                        UserInfo userInfo = new UserInfo();
                        if (_customerInfo.SalesUserID != null)
                        {
                            userInfo = YZ.GetDatabase(tttagKey).Get<UserInfo>(_customerInfo.SalesUserID.Value);
                            Link link = YZ.GetDatabase(tttagKey).Get<Link>(1);//系统管理员号码
                            var tel = "";
                            if (link != null && link.Tel != null)
                                tel = link.Tel.ToString();
                            //提醒到管理员 业务 客户的短信
                            #region
                            var snStr = tempSns.ToString();
                            var orderType = param.GetInt("OrderType");//订单类型 (1客主 2代客 3 录入 4 二级） 9-10
                            if (userInfo.Mobile.ToString().Length > 10 && orderType == 1)
                                SendMsg(userInfo.Mobile, userInfo.RealName, _customerInfo.NickName, snStr);  //业务
                            //TODU客户要用微信提醒
                            //if (userInfo.Mobile != _customerInfo.Mobile && _customerInfo.Mobile.Length > 10 && orderType == 2) //客户
                            //    SendMsg(_customerInfo.Mobile, "", "您", snStr);
                            if (userInfo.Mobile != tel && tel.Length > 10)
                                SendMsg(tel, "管理员", _customerInfo.NickName, snStr);//admin
                            #endregion
                        }
                        else
                        {
                            //PC
                            //Link link = YZ.GetDatabase(tttagKey).Get<Link>(1);//系统管理员号码
                            //var tel = "";
                            //if (link != null)
                            //    tel = link.Tel.ToString();
                            //if (tel.Length > 10)
                            //    SendMsg(tel, "管理员", _customerInfo.nickname, tempSns.ToString());//admin

                            //微信提醒
                            //TODO
                        }
                        return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(msg));
                    }
                    else
                        return CommonLog.MsgErrorInfo("可能已在订单中!");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("提交订单：程序错误：");
            }
        }
        #region
        public async Task<string> SubmitOrderByYiJi(string inventoryInfoParam, string token = "")
        {
            YIJIServiceReference.SubServiceClient subServiceClient = new YIJIServiceReference.SubServiceClient();
            return await subServiceClient.SubmitOrderAsync(inventoryInfoParam, token);
        }
        public string SubmitOrdersFromSub(string inventoryInfoParam)
        {
            //SubRetailReference.SubRetailClient subServiceClient = new SubRetailReference.SubRetailClient();
            //return   subServiceClient.SubmitOrdersFromSub(inventoryInfoParam);
            return "";
        }
        #endregion
        /// <summary>
        /// 录入订单 9-6
        /// </summary>
        /// <param name="entryOrderParam"></param>
        /// <returns></returns>
        public string EntryOrder(string entryOrderParam)
        {
            logParam = entryOrderParam;
            string tttagKey = CommonUrl.getURL(null, entryOrderParam);
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            IList<HashParam> param = JsonConvert.DeserializeObject<IList<HashParam>>(entryOrderParam);
            try
            {
                int Successful = 0, Failed = 0;//录入成功
                foreach (var items in param)
                {
                    //客户是否存在
                    CustomerInfo _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", items.GetString("CustomerNickName"));//通过CustomerNickName获取客户信息 12-23
                    if (_customer == null)
                    {
                        //客户不存在
                        _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", items.GetString("CustomerUserName"));//通过CustomerRealName获取客户信息 12-23
                        if (_customer == null)
                        {
                            _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", items.GetInt("CustomerUserID", 0));//通过CustomerID获取客户信息 9-26
                            if (_customer == null)
                            {
                                Failed++;//客户不存在
                            }
                        }
                    }
                    //客户存在
                    #region
                    OrderInfoResult _order = new OrderInfoResult();

                    _order.CustomerNickName = _customer.NickName;
                    //_order.CustomerRealName = _customer.RealName;
                    _order.CustomerID = _customer.CustomerID;
                    string UserName = items.GetString("PurchaseUser");
                    UserInfo _user = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.GetUserInfo", UserName);//采购UserName
                    if (_user != null)
                    {
                        _order.PurchaseUserID = _user.UserID;//采购ID
                    }
                    else
                    {
                        _order.PurchaseUserID = items.GetInt("PurchaseUserID", 0);//采购ID
                        if (_order.PurchaseUserID == -1)
                        {
                            _order.PurchaseUserID = Convert.ToInt32(_customer.PurchaseUserID);//采购ID
                        }
                    }
                    _order.InventoryAttribute = JsonConvert.SerializeObject(items);
                    _order.CreateTime = items.GetDataTime("CreateTime");//下单日期

                    _order.InventoryID = items.GetInt("InventoryID");//long 
                    _order.DeliveryTime = items.GetDataTime("PurchaseDate",DateTime.MinValue);
                    _order.PaymentStatus = 0;//0未支付 1已支付
                    _order.ReceiptStatus = 0;//0未支付 1已支付  
                    //int rowindex = items.GetInt("Index", 0);
                    //现货 定货 12-23
                    _order.Supplier = items.GetString("Supplier");
                    if (_order.Supplier.ToLower() == tttagKey)
                    {
                        //现货
                        _order.OrderStatus = 3;//待出货
                        _order.ArrivalTime = DateTime.Now;//到货日期 12-29
                    }
                    else
                    {
                        //定货
                        _order.OrderStatus = items.GetInt("OrderStatus", 0);//订单状态
                    }
                    //销售汇率
                    #region
                    SysSettingInfo setting = YZ.GetDatabase(tttagKey).QueryForObject<SysSettingInfo>("Syssetting.GetLooseSetting", null);
                    _order.SalesExchangerate = items.GetDecimal("SalesExchangerate", 0);//卖出汇率
                    if (setting != null)
                    {
                        _order.PurchaseExchangerate = setting.PurchaseExchangerate.Value;
                        if (_order.SalesExchangerate == 0)
                        {
                            _order.SalesExchangerate = setting.Rate;//售出汇率 9-6
                        }
                    }
                    else
                    {
                        //跳出
                        return _msgInfo.Replace("#code", "false").Replace("#msg", "无法录入,全局设置为空").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                    }
                    #endregion
                    //后台计算价格：白钻以退点为准；彩钻以总价为准 2017-02-24
                    #region
                    var IsFancy = items.GetInt("IsFancy", 0);
                    if (IsFancy == 0)
                    {
                        //计算Rapnet值(4C)
                        #region
                        RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                        _order.Rapnet = rap.GetPrice(_order);
                        if (_order.Rapnet > 0)
                        {
                            //白钻 = 重量 * Rap * 退点 * 汇率
                            _order.Confirmdiscount = items.GetDecimal("Confirmdiscount", 0);//卖出退点
                            _order.DiscountReturn = items.GetDecimal("SourceDiscountReturn", 0);
                            //买入价
                            _order.PriceUSD = items.GetDecimal("Weight").Value * _order.Rapnet.Value * ((100 + items.GetDecimal("SourceDiscountReturn", 0)) / 100);
                            //卖出价
                            _order.ConfirmUSD = items.GetDecimal("Weight").Value * _order.Rapnet * ((100 + items.GetDecimal("Confirmdiscount", 0)) / 100);
                            //卖出价
                            _order.ConfirmPrice = items.GetDecimal("Weight").Value * _order.Rapnet.Value * ((100 + items.GetDecimal("Confirmdiscount", 0)) / 100) * _order.SalesExchangerate.Value;
                        }
                        else
                        {
                            Failed++;//没有国际报价
                            continue;
                        }
                        #endregion
                    }
                    else if (IsFancy == 1)
                    {
                        //彩钻
                        _order.PriceUSD = items.GetDecimal("SourceDolarPerGrain", 0);
                        _order.ConfirmUSD = items.GetDecimal("PriceRMB", 0) / _order.SalesExchangerate;
                        _order.ConfirmPrice = items.GetDecimal("PriceRMB", 0);
                        _order.Confirmdiscount = null;//无退点
                        _order.DiscountReturn = null;
                    }
                    #endregion
                    if (!string.IsNullOrEmpty(items.GetString("CertNo")))
                    {
                        //订单是否已存在 9-27
                        OrderInfo _existOrder = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.IsExistOrder", _order);//判断是否已经存在订单 通过GIA和12345678判断 
                        if (_existOrder == null)
                        {
                            Successful++; //不重复，继续
                        }
                        else
                        {
                            Failed++;//订单已存在
                            continue;
                        }
                    }
                    else
                    {
                        //证书号不录，无法查询是否重复
                        Successful++;
                    }
                    #endregion
                    //提交事务
                    #region
                    using (ITransaction trans_entryOrder = YZ.GetTransaction(tttagKey))
                    {
                        int entryOrderResult = YZ.GetDatabase(tttagKey).Add(_order);
                        if (entryOrderResult > 0)
                        {
                            try
                            {
                                trans_entryOrder.CommitTransaction(); //触发事务
                                //数据中心下架(当InventoryID存在)
                                #region
                                if (_order.Supplier.ToLower() == tttagKey) //现货才提交到中心
                                {
                                    if (!string.IsNullOrEmpty(items.GetString("CertNo")) && _order.InventoryID != null)
                                    {
                                        //先将字符转字符数组，然后将字符数组转整形数组                            
                                        int[] InventoryIDs = new int[1];
                                        InventoryIDs[0] = Convert.ToInt32(_order.InventoryID);//不能为空                            
                                        TransmissionOrderResult submitOrderResult = AllPublic.OprationOrders(InventoryIDs, "add", tttagKey);//提交订单 InventoryID  (OprationOrders 包含了提交订单、删除订单 和获取订单)
                                    }
                                }
                                #endregion
                            }
                            catch (Exception)
                            {
                                trans_entryOrder.RollBackTransaction();//回滚事务
                            }
                        }
                    }
                    #endregion
                }
                return _msgInfo.Replace("#code", "true").Replace("#msg", "录入结果").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return _msgInfo.Replace("#code", "false").Replace("#msg", "内部错误").Replace("#succ", JsonConvert.SerializeObject(0)).Replace("#fail", JsonConvert.SerializeObject(0));
            }
        }
        /// <summary>
        /// 打印出货单 9-20
        /// </summary>
        /// <param name="deliveryOrdersParam"></param>
        /// <returns></returns>
        public string PrintShipOrders(string printShipOrdersParam)
        {
            logParam = printShipOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(printShipOrdersParam);
            string tttagKey = CommonUrl.getURL(param, printShipOrdersParam);
            string FileName = "出货单 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            decimal? TotalRMB = 0;//9-24
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr>");
                OutFileContent.Append("<td colspan='8'></td><td colspan='2'>出货单明细</td><td colspan='8'></td></tr>");//总RMB
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>编号</td>");
                OutFileContent.Append("<td>货号</td>");
                OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                //OutFileContent.Append("<td>尺寸</td>");
                OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>证号</td>");
                OutFileContent.Append("<td>报价</td>");
                OutFileContent.Append("<td>汇率</td>");
                OutFileContent.Append("<td>退点</td>");
                OutFileContent.Append("<td>RMB</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>下单</td>");
                //OutFileContent.Append("<td>描述</td>");
                //OutFileContent.Append("<td>备注</td>");
                //OutFileContent.Append("<td>状态</td>");
                OutFileContent.Append("<td>收款</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                IList<OrderInfoResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetOrderByIDs", param);
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        InventoryInfoResult inventoryInfo = JsonConvert.DeserializeObject<InventoryInfoResult>(OrderList[i].InventoryAttribute);

                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.SN + "</td>");
                        columnValue.Append("<td>" + ShapeFormat(inventoryInfo.Shape) + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Weight + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Color + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Clarity + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Cut + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Polish + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Symmetry + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Fluorescence + "</td>");
                        //columnValue.Append("<td>" + OrderList[i].Measurement + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.CertType + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.CertNo + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Confirmdiscount + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmPrice + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");//客户昵称 9-14
                        columnValue.Append("<td>" + Convert.ToDateTime(OrderList[i].CreateTime).ToString("yyyy-MM-dd").Replace("0001-01-01", "-") + "</td>");
                        //columnValue.Append("<td>" + OrderList[i].Milky + " " + OrderList[i].Hue + "</td>");//货品奶咖 9-20
                        //columnValue.Append("<td>" + OrderList[i].Remarks + "</td>");//客户备注 9-20
                        //columnValue.Append("<td>" + OrderStatusFormat(OrderList[i].OrderStatus) + "</td>");
                        columnValue.Append("<td>" + PaymentStatusFormat(OrderList[i].PaymentStatus) + "</td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                        TotalRMB += OrderList[i].ConfirmPrice;//
                    }
                    OutFileContent.Clear();
                    #region 统计
                    OutFileContent.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");
                    OutFileContent.Append("<td colspan='15'></td><td style='font-weight:bold'>" + Math.Round(Convert.ToDecimal(TotalRMB)) + "</td><td colspan='3'></td></tr>");//总RMB
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    //返回文件下载地址 http://localhost:3952/excel/2016-08-18 08-03-03.xls
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 获取出货单订单
        /// </summary>
        /// <returns></returns>
        public string GetShipOrders(string getShipOrdersParam)
        {
            logParam = getShipOrdersParam;
            string tttagKey = CommonUrl.getURL(null, getShipOrdersParam);
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(getShipOrdersParam);
            try
            {
                IList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByShipNo", param);//IList不需要PageSize和PageIndex， PageList需要PageSize和PageIndex
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));//_ordersInfo.Data 不含_ordersInfo.FooterData
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载订单失败，程序错误");
            }
        }
        /// <summary>
        /// 订单支付
        /// </summary>
        /// <param name="editShipNoParam"></param>
        /// <returns></returns>
        public string PayOrders1(string payOrdersParam)
        {
            logParam = payOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(payOrdersParam);
            string tttagKey = CommonUrl.getURL(param, payOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    OrderInfo _order = new OrderInfo();
                    CustomerInfo _customer = new CustomerInfo();
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", _orderIDs[i]);
                        if (_order != null)
                        {
                            //付款状态为未支付0
                            if (_order.PaymentStatus == 0)
                            {
                                _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", _order.CustomerID);
                                if (_customer != null)
                                {
                                    //客户当前余额大于当前订单应付金额（每个订单先四舍五入后再扣款10-11）
                                    if (_customer.Balance >= Math.Round(Convert.ToDecimal(_order.ConfirmPrice)) && _customer.Balance > 0) //Round 四舍六入五取偶
                                    {
                                        //第一步：扣除客户的余额
                                        _customer.Balance = -(Math.Round(Convert.ToDecimal(_order.ConfirmPrice)));
                                        using (ITransaction trans_editBalance = YZ.GetTransaction(tttagKey))
                                        {
                                            int editBalanceResult = trans_editBalance.Update("Customer.EditBalance", _customer);//客户余额更新结果
                                            if (editBalanceResult > 0)
                                            {
                                                _order.PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                _order.PayTime = DateTime.Now;//支付时间
                                                using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                                {
                                                    int editOrderResult = trans_editOrder.Edit(_order);
                                                    //第二步：更新订单单条成功后，就执行事务
                                                    if (editOrderResult > 0)
                                                    {
                                                        //第三步：写扣款记录（暂时不开发 8-28）
                                                        try
                                                        {
                                                            trans_editOrder.CommitTransaction(); //触发入库事务
                                                            //更新订单成功后，更新客户余额
                                                            try
                                                            {
                                                                trans_editBalance.CommitTransaction(); //触发入库事务
                                                                Successful++;
                                                            }
                                                            catch (Exception)
                                                            {
                                                                trans_editBalance.RollBackTransaction();//回滚事务
                                                            }
                                                        }
                                                        catch (Exception)
                                                        {
                                                            trans_editOrder.RollBackTransaction();//回滚事务
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //更新订单失败
                                                        Failed++;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //更新客户余额失败
                                                Failed++;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //客户余额不足
                                        Failed++;
                                    }
                                }
                                else
                                {
                                    //客户不存在
                                    Failed++;
                                }
                            }
                            else
                            {
                                //订单已支付1
                                Failed++;
                            }
                        }
                        else
                        {
                            //订单不存在
                            Failed++;
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "支付成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("支付失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("支付失败");
            }
        }
        //删除现货订单 （备用表，非订单表）
        public string DelOrdersByOwner(string delOrdersParam)
        {
            return NewDelOrders(delOrdersParam, true);
        }
        /// <summary>
        /// 删除订单 9-29
        /// </summary>
        /// <param name="payOrdersParam"></param>
        /// <returns></returns>
        public string DelOrders(string delOrdersParam)
        {
            return NewDelOrders(delOrdersParam, false);
        }
        private string NewDelOrders(string delOrdersParam, bool isStock)
        {
            logParam = string.Format("delOrdersParam:{0},isStock:{1}", delOrdersParam, isStock.ToString());
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            if (isStock) //现货
                            {
                                delOrdersResult = trans_delOrders.Delete("Order.DelOrdersOwner", _orderIDs[i]);//删除结果
                            }
                            else
                            {
                                delOrdersResult = trans_delOrders.Delete("Order.DelOrders", _orderIDs[i]);//删除结果
                            }
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }
        /// <summary>
        /// 导出我的订单（仅客户）
        /// </summary>
        /// <param name="downloadOrderParam"></param>
        /// <returns></returns>
        public string ExportOrders(string exportOrdersParam)
        {
            logParam = exportOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(exportOrdersParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, exportOrdersParam);
            string FileName = "MyOrder " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<OrderInfoResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.ExportOrder", param);//订单IList
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>货号</td>");
                OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                //OutFileContent.Append("<td>尺寸</td>");
                OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>证书号</td>");
                OutFileContent.Append("<td>国际报价</td>");
                OutFileContent.Append("<td>销售汇率</td>");
                OutFileContent.Append("<td>卖出退点</td>");
                OutFileContent.Append("<td>卖出RMB</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>下单日期</td>");
                OutFileContent.Append("<td>订单状态</td>");
                OutFileContent.Append("<td>支付状态</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        InventoryInfoResult inventoryInfo = JsonConvert.DeserializeObject<InventoryInfoResult>(OrderList[i].InventoryAttribute);
                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.SN + "</td>");
                        columnValue.Append("<td>" + ShapeFormat(inventoryInfo.Shape) + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Weight + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Color + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Clarity + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Cut + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Polish + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Symmetry + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.Fluorescence + "</td>");
                        //columnValue.Append("<td>" + OrderList[i].Measurement + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.CertType + "</td>");
                        columnValue.Append("<td>" + inventoryInfo.CertNo + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Confirmdiscount + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmPrice + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CreateTime + "</td>");
                        columnValue.Append("<td>" + CustomerOrderStatusFormat(OrderList[i].OrderStatus) + "</td>");
                        columnValue.Append("<td>" + PaymentStatusFormat(OrderList[i].PaymentStatus) + "</td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + OrderList.Count+ "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    //返回文件下载地址
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在，没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出订单失败:");
            }
        }

        /// <summary>
        /// 获取单个订单信息
        /// </summary>
        /// <param name="customerInfoParam"></param>
        /// <returns></returns>
        public string GetOrderInfo(string orderInfoParam)
        {
            logParam = orderInfoParam;
            HashParam param = Json.Deserialize<HashParam>(orderInfoParam);
            string tttagKey = CommonUrl.getURL(param, orderInfoParam);
            //templateJSON
            try
            {
                OrderInfo order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", param.GetInt("OrderID"));
                //OrderInfo order = YZ.GetDatabase(tttagKey).Get<OrderInfo>(Convert.ToInt32(param.OrderID));////有坑 不能用YZ.GetDatabase(tttagKey).Get<OrderInfo>()获取
                if (order != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(order));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取订单信息失败，请检查订单标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 支付出货单
        /// </summary>
        /// <param name="payShipNoParam"></param>
        /// <returns></returns>
        public string EditShipNo(string editShipNoParam)
        {
            logParam = editShipNoParam;
            string tttagKey = CommonUrl.getURL(null, editShipNoParam);
            //ShipNo
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(editShipNoParam);
            try
            {
                //如果客户的余额大于出货单的应付金额，则可更新订单状态为已支付1；否则支付失败.
                OrderInfoResult _shipInfo = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfoResult>("Order.GetShipInfo", param);//单个出货单信息，通过ShipNo
                if (_shipInfo != null)
                {
                    CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", _shipInfo);//单个客户信息，通过CustomerID
                    if (_customerInfo != null)
                    {
                        //客户余额大于等于当前出货单应付金额
                        if (_customerInfo.Balance >= Math.Round(_shipInfo.Balance))
                        {
                            IList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByShipNo", param);//IList不需要PageSize和PageIndex， PageList需要PageSize和PageIndex
                            if (_ordersInfo != null && _ordersInfo.Count > 0)
                            {
                                //扣除客户的余额
                                _customerInfo.CustomerID = Convert.ToInt32(_shipInfo.CustomerID);//客户ID
                                _customerInfo.Balance = -(_shipInfo.Balance);
                                using (ITransaction trans_editBalance = YZ.GetTransaction(tttagKey))
                                {
                                    int editBalanceResult = trans_editBalance.Update("Customer.EditBalance", _customerInfo);//客户余额更新结果
                                    if (editBalanceResult > 0)
                                    {
                                        DateTime payTime = DateTime.Now;//支付时间
                                        for (int i = 0; i < _ordersInfo.Count; i++)
                                        {
                                            _ordersInfo[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                            _ordersInfo[i].PayTime = payTime;
                                            using (ITransaction trans_editShipNo = YZ.GetTransaction(tttagKey))
                                            {
                                                int editShipNoResult = trans_editShipNo.Edit(_ordersInfo[i]);
                                                //单条成功后，就执行入库订单事务
                                                if (editShipNoResult > 0)
                                                {
                                                    try
                                                    {
                                                        trans_editShipNo.CommitTransaction(); //触发入库事务
                                                    }
                                                    catch (Exception)
                                                    {
                                                        trans_editShipNo.RollBackTransaction();//回滚事务
                                                    }
                                                }
                                            }
                                        }
                                        //订单全部更新成功后，更新客户余额
                                        try
                                        {
                                            trans_editBalance.CommitTransaction(); //触发入库事务
                                        }
                                        catch (Exception)
                                        {
                                            trans_editBalance.RollBackTransaction();//回滚事务
                                        }
                                        return CommonLog.MsgSuccessInfo("支付成功");
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo("支付失败:更新客户余额失败");
                                    }
                                }
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("支付失败:订单不存在");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("支付失败:客户账户余额不足,请先充值");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("支付失败:客户不存在");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("支付失败:出货单不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载订单失败，程序错误");
            }
        }

        /// <summary>
        /// 导出裸钻
        /// </summary>
        /// <param name="exportParam"></param>
        /// <returns></returns>
        public string GetExportUrl(string exportParam)
        {
            logParam = exportParam;
            string tttagKey = CommonUrl.getURL(null, exportParam);
            //参数可全空
            //#msg 和"#msg" 
            try
            {
                string guid = Guid.NewGuid().ToString();
                //var objParams = JsonConvert.DeserializeObject<JObject>(exportParam); //解析参数到对像JObject,有参时用到
                var lastStr = "";
                //lastStr = MyHttpRequest.DictSortAnd2Str(objParams).ToString(); //排序参数,有参时用到
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = "{}", RequestUrl = GlobalConfig.GetExportUrl };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST);
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 查看取货单
        /// </summary>
        /// <returns></returns>
        public string GetDeliverys(string getDeliverysParam)
        {
            logParam = getDeliverysParam;
            string tttagKey = CommonUrl.getURL(null, getDeliverysParam);
            //取货单日期（即 结束发货日期）
            //
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"totalrmb\":#rmb,\"totalusd\":#usd}";
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(getDeliverysParam);
            //统计
            decimal? TotalRMB = 0;//总人民币 9-22
            decimal? TotalUSD = 0;//总美金
            try
            {
                PageList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.DeliveryOrders", param, param.pageSize, param.pageIndex);//查看 9-28
                if (_ordersInfo != null && _ordersInfo.Data.Count > 0)
                {
                    for (int i = 0; i < _ordersInfo.Data.Count; i++)
                    {
                        TotalRMB += _ordersInfo.Data[i].ConfirmPrice;
                        TotalUSD += _ordersInfo.Data[i].PriceUSD;
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", JsonConvert.SerializeObject(_ordersInfo)).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
                    //return  CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));//_ordersInfo.Data 不含_ordersInfo.FooterData
                }
                else
                {
                    //空
                    return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("没有任何记录")).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("加载失败，程序错误")).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
            }
        }
        /// <summary>
        /// 查询到货日期
        /// </summary>
        /// <param name="getDeliverysParam"></param>
        /// <returns></returns>
        public string GetArrivals(string getArrivalsParam)
        {
            logParam = getArrivalsParam;
            string tttagKey = CommonUrl.getURL(null, getArrivalsParam);
            //取货单日期（即 结束发货日期）
            //
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"totalrmb\":#rmb,\"totalusd\":#usd}";
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(getArrivalsParam);
            //统计
            decimal? TotalRMB = 0;//总人民币 9-22
            decimal? TotalUSD = 0;//总美金
            try
            {
                PageList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.ArrivalOrders", param, param.pageSize, param.pageIndex);//9-28
                if (_ordersInfo != null && _ordersInfo.Data.Count > 0)
                {
                    for (int i = 0; i < _ordersInfo.Data.Count; i++)
                    {
                        TotalRMB += _ordersInfo.Data[i].ConfirmPrice;
                        TotalUSD += _ordersInfo.Data[i].PriceUSD;
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", JsonConvert.SerializeObject(_ordersInfo)).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
                    //return  CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));//_ordersInfo.Data 不含_ordersInfo.FooterData
                }
                else
                {
                    //空
                    return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("没有任何记录")).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("加载失败，程序错误")).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB)).Replace("#usd", JsonConvert.SerializeObject(TotalUSD));
            }
        }
        //录单
        /// <summary>
        /// 录入的参数是否重复 9-27
        /// </summary>
        /// <returns></returns>
        public string EntryCheck(string entryCheckParam)
        {
            logParam = entryCheckParam;
            string tttagKey = CommonUrl.getURL(null, entryCheckParam);
            IList<HashParam> param = JsonConvert.DeserializeObject<IList<HashParam>>(entryCheckParam);
            IList<string> result = new List<string>();
            HashSet<string> hs = new HashSet<string>();
            try
            {
                foreach (var item in param)
                {
                    var certype = item.GetString("CertType");
                    var cerno = item.GetString("CertNo");
                    if (string.IsNullOrEmpty(certype) || string.IsNullOrEmpty(cerno))
                    {
                        continue;
                    }
                    if (certype != "NN" && cerno != "")
                    {
                        var key = certype[0] + cerno;
                        if (hs.Contains(key))
                        {
                            result.Add(key);
                        }
                        else
                        {
                            hs.Add(key);
                        }
                    }
                }
                if (result.Count > 0)
                {
                    //页面参数有重复 9-27
                    return CommonLog.MsgErrorInfo(JsonConvert.SerializeObject(result));
                }
                else
                {
                    return CommonLog.MsgSuccessInfo("表单无重复");//页面参数无重复 9-27
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("检查失败");
            }
        }


        /// <summary>
        /// 导出录单模板
        /// </summary>
        /// <returns></returns>
        public string DownEntryTemplate()
        {
            //string FileName = "upload_template.xlsx";//文件名
            string FileName = "entry_template.xls";//文件名
            try
            {
                //判断文件夹是否存在
                if (Directory.Exists(HttpContext.Current.Server.MapPath("/excel/")) == true)
                {
                    //判断文件是否存在
                    if (File.Exists(HttpContext.Current.Server.MapPath("/excel/") + FileName))
                    {
                        return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("下载失败，文件不存在");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("下载失败，文件夹不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("下载失败:");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oType">订单类型，成品统包</param>
        /// <param name="obj"></param>
        /// <param name="titleBuilder"></param>
        /// <param name="contentBuilder"></param>
        public void GetObjectProperties(string oTypeName, object obj, ref StringBuilder contentBuilder, bool isTitle = false)
        {
            Type type = obj.GetType();
            var pros = type.GetProperties();
            contentBuilder.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
            foreach (var p in pros)
            {
                if (isTitle)
                { //添加表头
                    var title = getTitleNameByDBTitle(oTypeName, p.Name);
                    if (title != "")
                        contentBuilder.Append(string.Format("<td>{0}</td>", getTitleNameByDBTitle(oTypeName, p.Name)));
                    else
                    {
                        addNull.Add(p.Name, p.Name);
                    }
                }
                else
                    //Console.Write(p.Name + p.GetValue(obj) + " ");
                    if (!addNull.ContainsKey(p.Name))
                    contentBuilder.Append(string.Format("<td>{0}</td>", p.GetValue(obj)));
            }
            contentBuilder.Append("</tr>");//行开始
        }
        public string getTitleNameByDBTitle(string oTypeName, string oType)
        {
            Dictionary<string, Dictionary<string, string>> dict = new Dictionary<string, Dictionary<string, string>>();
            dict = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(File.ReadAllText(HttpContext.Current.Server.MapPath("dbdict.json")));
            if (dict != null)
            {
                var v = dict[oTypeName];
                foreach (var item in v)
                {
                    if (item.Key.ToLower() == oType.ToLower())
                    {
                        return v[item.Key];
                    }
                }
            }
            return "";
        }
        #endregion
        #region 成品相关

        private string ProductReviseOrders<T>(string productOrdersParam, string sqlName)
        {
            logParam = productOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(productOrdersParam);
            string tttagKey = CommonUrl.getURL(param, productOrdersParam);
            var returnJson = "";
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        dynamic _order = YZ.GetDatabase(tttagKey).QueryForObject<T>(sqlName + "Order.GetOrderByID", _orderIDs[i]);//本来是想批量的，不过这个场景只有单个修改
                        if (_order != null)
                        {
                            _order.ConfirmPrice = Convert.ToDecimal(param.GetString("ConfirmPrice"));
                            if (param.ContainsKey("SalesExchangerate") && param.GetString("SalesExchangerate") != "")//其它订单不支持汇率
                            {
                                _order.SalesExchangerate = Convert.ToDecimal(param.GetString("SalesExchangerate"));//销售汇率(默认选择系统);
                            }
                            int v = YZ.GetDatabase(tttagKey).Edit((BaseEntity)_order);  //这里的dynamic一定要强转成BaseEntity，否则找不到Edit 
                            returnJson = CommonLog.MsgErrorInfo("改价成功");
                        }
                        else
                        {
                            returnJson = CommonLog.MsgErrorInfo("改价失败，没有此订单");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                returnJson = CommonLog.MsgErrorInfo("改价：程序错误");
            }
            return returnJson;
        }


        //删除作废订单
        public string RingDelOrders(string delOrdersParam)
        {
            logParam = delOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            delOrdersResult = trans_delOrders.Delete("RingOrder.DelOrders", _orderIDs[i]);//删除结果
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }



        /// <summary>
        /// 单个订单
        /// </summary>
        /// <param name="orderInfoParam"></param>
        /// <returns></returns>
        public string GetRingOrderInfo(string orderInfoParam)
        {
            return AllPublic.GetRingOrderInfo<OrderInfo>(orderInfoParam);
        }


        /// <summary>
        /// 成品公用模块 成品搜索/筛选
        /// </summary>
        /// <param name="getInlaysParam"></param>
        /// <returns></returns>
        private string PartByGetInlays(string getInlaysParam, string key)
        {
            string requestUrl = GlobalConfig.TransmissionInlaysSearchUrl;
            return CRetails.AllProduct(key, getInlaysParam, key, requestUrl);
        }
        /// <summary>
        /// //成品列表
        /// </summary>
        /// <param name="getInlaysParam"></param>
        /// <returns></returns>
        public string GetInlays(string getInlaysParam)
        {
            string tttagKey = CommonUrl.getURL(null, getInlaysParam);
            return GetProduct<RingInfoResult>(tttagKey, getInlaysParam, GlobalConfig.TransmissionInlaysSearchUrl, GoodsType.Ring);
        }
        /// <summary>
        /// 单个成品查询
        /// </summary>
        /// <param name="getInlayParam"></param>
        /// <returns></returns>
        public string GetInlay(string getInlayParam)
        {
            logParam = getInlayParam;
            HashParam param = Json.Deserialize<HashParam>(getInlayParam);
            string tttagKey = CommonUrl.getURL(param, getInlayParam);
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数
                RequestInfo rif = new RequestInfo() { RequestJson = getInlayParam, RequestUrl = string.Format(GlobalConfig.TransmissionInlaysOprateUrl, param.GetInt("ID")) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //(Rapnet)
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else
                {
                    Ring product = CalProductPrice<Ring>(param, responseJson, GoodsType.Ring, tttagKey);
                    responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));

                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载单个成品失败，程序错误");
            }
        }
        //修改成品
        public string ModInlays(string modInlaysParam)
        {
            logParam = modInlaysParam;
            string tttagKey = CommonUrl.getURL(null, modInlaysParam);
            //参数可全空
            //#msg 和"#msg" 
            Ring ring = Json.Deserialize<Ring>(modInlaysParam);
            try
            {
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(modInlaysParam);
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = modInlaysParam, RequestUrl = string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ring.ID) };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT);
                if (responseJson.Contains(".py"))
                {
                    if (ConfigurationManager.AppSettings["IsDebug"].ToString() == "true")
                    {
                        responseJson = CommonLog.MsgErrorInfo(responseJson);
                    }
                    else
                    {
                        responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                    }
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        //添加成品
        public string AddInlays(string modInlaysParam)
        {
            logParam = modInlaysParam;
            string tttagKey = CommonUrl.getURL(null, modInlaysParam);
            //参数可全空
            //#msg 和"#msg" 
            Ring ring = Json.Deserialize<Ring>(modInlaysParam);
            try
            {
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(modInlaysParam);
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = modInlaysParam, RequestUrl = string.Format(GlobalConfig.TransmissionInlaysOprateUrl, "") };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST);
                if (responseJson.Contains(".py") && responseJson.Contains("Error:"))
                {
                    responseJson = "远程接口出错,出错信息：" + responseJson.Substring(responseJson.IndexOf("Error:") + 6, responseJson.Length - (responseJson.IndexOf("Error:") + 6));
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误" + responseJson);
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("新增成品失败，程序错误");
            }
        }
        //删除成品
        public string DeleteInlays(string delInlaysParam)
        {
            logParam = delInlaysParam;
            string tttagKey = CommonUrl.getURL(null, delInlaysParam);
            //参数可全空
            //#msg 和"#msg" 
            Ring ring = Json.Deserialize<Ring>(delInlaysParam);
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数
                RequestInfo rif = new RequestInfo() { RequestJson = delInlaysParam, RequestUrl = string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ring.ID) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.DELETE); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除成品失败，程序错误");
            }
        }
        #endregion
        #region 彩宝相关
        /// <summary>
        /// //彩宝列表
        /// </summary>
        /// <param name="getGemsParam"></param>
        /// <returns></returns>
        public string GetGems(string getGemsParam)
        {
            string tttagKey = CommonUrl.getURL(null, getGemsParam);
            return GetProduct<GemInfoResult>(tttagKey, getGemsParam, GlobalConfig.TransmissionGemSearchUrl, GoodsType.Gem);
        }
        /// <summary>
        /// 单个彩宝查询
        /// </summary>
        /// <param name="getGemParam"></param>
        /// <returns></returns>
        public string GetGem(string getGemParam)
        {
            logParam = getGemParam;
            HashParam param = Json.Deserialize<HashParam>(getGemParam);
            string tttagKey = CommonUrl.getURL(param, getGemParam);
            string responseJson = CRetails.AllProduct(tttagKey, getGemParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, param.GetInt("ID")), "get");
            if (responseJson.Contains(".py") || responseJson.Contains("程序错误"))
            {
                return responseJson.Replace("false", "\"false\"").Replace("#msg", "远程服务错误");
            }
            else
            {
                Gem product = CalProductPrice<Gem>(param, responseJson, GoodsType.Gem, tttagKey);
                responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));

            }
            return responseJson;
        }
        //修改彩宝
        public string ModGems(string modGemsParam)
        {
            string tttagKey = CommonUrl.getURL(null, modGemsParam);
            Gem gem = Json.Deserialize<Gem>(modGemsParam);
            return CRetails.AllProduct(tttagKey, modGemsParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, gem.ID), "put");
        }
        //添加彩宝
        public string AddGems(string modGemsParam)
        {
            string tttagKey = CommonUrl.getURL(null, modGemsParam);
            Gem gem = Json.Deserialize<Gem>(modGemsParam);
            return CRetails.AllProduct(tttagKey, modGemsParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, ""), "post");
        }
        //删除彩宝
        public string DeleteGems(string delGemsParam)
        {
            string tttagKey = CommonUrl.getURL(null, delGemsParam);
            Gem gem = Json.Deserialize<Gem>(delGemsParam);
            return CRetails.AllProduct(tttagKey, delGemsParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, gem.ID), "delete");
        }


        /// <summary>
        /// 移除购物车
        /// </summary>
        /// <param name="ringCartId"></param>
        /// <returns></returns>
        public string RemoveGemsCart(string removeFromCartParam)
        {
            return DelAllCartByCustomerIdAndProductIds(removeFromCartParam, "GemIDs", "Gem_Cart.DeleteByGemIDs");
        }



        //删除作废订单
        public string GemDelOrders(string delOrdersParam)
        {
            logParam = delOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            delOrdersResult = trans_delOrders.Delete("GemOrder.DelOrders", _orderIDs[i]);//删除结果
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }


        #endregion 彩宝结束
        #region 统包Parcel 方法
        /// <summary>
        /// //统包列表
        /// </summary>
        /// <param name="getParcelsParam"></param>
        /// <returns></returns>
        public string GetParcels(string getParcelsParam)
        {
            string tttagKey = CommonUrl.getURL(null, getParcelsParam);
            return GetProduct<ParcelInfoResult>(tttagKey, getParcelsParam, GlobalConfig.TransmissionParcelsSearchUrl, GoodsType.Parcel);
        }
        /// <summary>
        /// 通过参数获取所有产品并计算价格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="getProductParam"></param>
        /// <param name="searchUrl"></param>
        /// <param name="lib"></param>
        /// <returns></returns>
        private string GetProduct<T>(string tttagKey, string getProductParam, string searchUrl, int lib, CustomerInfo customer = null,string secondSn="")
        {
            logParam = getProductParam;
            //SearchProductLogs(logParam, lib.ToString());
            try
            {
                HashParam param = Json.Deserialize<HashParam>(getProductParam);//组装前 {"IsStock":1,"limit":100,"useDict":true}

                //现货搜索
                var responseJson = "";
                var isStock = false;
                if (param.ContainsKey("IsMyStock") && param.GetBool("IsMyStock")) //此处要多传一个IsStock或IsMyStock字段因为前段也可能搜索现货
                { 
                    isStock = true;//现货
                    param["Supplier"] = tttagKey;
                    param.Remove("IsMyStock");
                    getProductParam = JsonConvert.SerializeObject(param);//组装后 {"limit":100,"useDict":true,"Supplier":"HST"}  
                }
                if (param.ContainsKey("ParentKey") && param["ParentKey"].ToString() != ""&& !isStock)
                {
                    param["TagKey"] = tttagKey.Split(new string[] { "__" }, StringSplitOptions.None)[0]; //上一级需要加上一级自己的key
                    if (!param.ContainsKey("SecondSN"))
                        param["SecondSN"] = tttagKey; //上一级需要加上一级自己的key
                    param["GoodsType"] = lib;
                    var token = param.GetString("ParentKey");

                    //param.Remove("IsStock");
                    param.Remove("CustomerID"); //移除二级本身的客户ID   
                    if (param.ContainsKey("ErJiMark"))
                    {
                        var typeStr = param["ErJiMark"].ToString();
                        param.Remove("ErJiMark");         //这些key不能带到数据中心
                        if (typeStr == "2LSto1LS")//数据来源 2级零售版本，它的数据来源是一级零售
                        { 
                            responseJson = QueryProductDataFromUpper(JsonConvert.SerializeObject(param));
                        }
                        else if (typeStr == "2LSto1PF")//这里是给其他的二级查货
                        {    
                            responseJson = GetProductsByYiJi(JsonConvert.SerializeObject(param),param.GetString("ParentKey"));
                        }
                        else
                        {
                            //TODO
                        }
                    }
                    else
                    {
                        //TODO 
                    }
                }
                else
                {
                    responseJson = CRetails.AllProduct(tttagKey, getProductParam, searchUrl, "post");
                }
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else if (responseJson.Contains("result\": false"))
                {
                    responseJson = CommonLog.MsgErrorInfo("未知错误");
                }
                else
                {
                    if (param.ContainsKey("onlyCount") && param["onlyCount"].ToString().ToLower() == "true")//onlyCount
                    {
                        return responseJson;
                    }
                    dynamic result = null;
                    HashParam _param = JsonConvert.DeserializeObject<HashParam>(responseJson);
                    if (_param.ContainsKey("msgcode") && _param.GetBool("msgcode") && _param.ContainsKey("msginfo") && _param.GetString("msginfo").Length > 30) //有时data直接为[] 但是查询正确，操蛋
                    {
                        responseJson = _param.GetString("msginfo");
                        result = JsonConvert.DeserializeObject<T>(responseJson); //解析结果，转成PageList<InventoryInfoResult>格式 
                    }
                    else
                    {
                        result = JsonConvert.DeserializeObject<T>(responseJson);
                    } 
                    if (!isStock) //非现货请求计算价格,现货展示原价（底价）
                    {
                        //{\"records\": 75, \"rows\": [{\"Category
                        //计算价格
                        if (result.rows.Count > 0)
                        {
                            //SystemSetting setting = new SystemSetting(lib);
                            int goodsType = 0;
                            string filterUrl = GoodsType.GetGoodsFilters(lib, ref goodsType);
                            SysSettingInfo settingInfo = GetSystemSetting(lib, goodsType, tttagKey);
                            //客户倍率
                            decimal customerRate = 1;
                            if (customer != null)
                            {
                                switch (lib)
                                {
                                    case GoodsType.Diamond:
                                        customerRate = customer.Rebate ?? 1; break;
                                    case GoodsType.Ring:
                                        customerRate = customer.RingRebate ?? 1; break;
                                    case GoodsType.Parcel:
                                        customerRate = customer.ParcelRebate ?? 1; break;
                                    case GoodsType.Gem:
                                        customerRate = customer.GemRebate ?? 1; break;
                                    case GoodsType.Emerald:
                                        customerRate = customer.EmeraldRebate ?? 1; break;
                                    case GoodsType.PrimeGolds:
                                        customerRate = customer.PrimeGoldRebate ?? 1; break;
                                        //case GoodsType.InlaySettings:
                                        //    customerDisc = customerInfo.InlaySettingsRebate ?? 1; break;
                                }
                            }
                            //供应商折扣 
                            foreach (var item in result.rows)
                            {
                                if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")
                                {
                                    if (goodsType == GoodsType.InlaySettings)
                                    {
                                        item.GoldPrice = item.CustomerGoldPrice;
                                        item.Wastage = item.CustomerWastage;
                                        item.SideLaborFee = item.CustomerSideLaborFee;
                                        item.LaborFee = item.CustomerLaborFee;
                                        item.SidePrice = item.CustomerSidePrice;
                                        item.Insurance = item.CustomerInsurance;
                                    }
                                }
                                CRetails.CalcPrice<T>(item, tttagKey, goodsType, settingInfo, customerRate, customer, secondSn); 
                            }
                        }
                    }
                    responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(result));
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("错误信息：" + ex.ToString());
            }
        }

         
        /// <summary>
        /// 单个统包查询
        /// </summary>
        /// <param name="getParcelParam"></param>
        /// <returns></returns>
        public string GetParcel(string getParcelParam)
        {
            logParam = getParcelParam;
            HashParam param = Json.Deserialize<HashParam>(getParcelParam);
            string tttagKey = CommonUrl.getURL(param, getParcelParam);
            string responseJson = CRetails.AllProduct(tttagKey, getParcelParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, param.GetInt("ID")), "get");
            if (responseJson.Contains(".py") || responseJson.Contains("程序错误"))
            {
                return CommonLog.MsgErrorInfo("远程服务错误");
            }
            else
            {
                Parcels product = CalProductPrice<Parcels>(param, responseJson, GoodsType.Parcel, tttagKey);
                responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));

            }
            return responseJson;
        }
        /// <summary>
        /// 计算所有产品 的价格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <param name="productJson"></param>
        /// <param name="setting"></param>
        /// <returns></returns>
        private T CalProductPrice<T>(HashParam param, string productJson, int settingType, string tttagKey)
        {
            dynamic setting = GoodsType.GetSystemSetting<SysSettingInfo>(tttagKey, settingType); //settingType);
            dynamic product = JsonConvert.DeserializeObject<T>(productJson);
            //现货不计算价格
            if (!param.ContainsKey("IsStock") && !param.ContainsKey("IsMyStock")) //此处要多传一个IsStock或IsMyStock字段因为前段也可能搜索现货
            {
                int goodsType = 0;
                string filterUrl = GoodsType.GetGoodsFilters(settingType, ref goodsType);
                SysSettingInfo settingInfo = GetSystemSetting(settingType, goodsType, tttagKey);
                decimal settingRate = 1;
                if (settingType == GoodsType.PrimeGolds || settingType == GoodsType.InlaySettings)
                {
                    //暂时设置空托全局
                    settingRate = 1; //GetGroupAmount(settingInfo, product.GoldPrice);//全局折扣
                }
                else
                {
                    //settingRate = GetGroupAmount(settingInfo, product.Price);//全局折扣
                    settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, product.Price, tttagKey);
                }
                //decimal disc = setting.GetGlobalFancyDiscountReturn(); //全局折扣
                //if (param.ContainsKey("CustomerID"))  //微信没有客户折扣
                //{
                //    //客户折扣GetCustomerDiscBySettingType(settingType, param);
                //    disc = disc * GetCustomerDiscBySettingType(settingType, param);
                //}
                //供应商折扣
                decimal supplierDisc = 0;
                //获取当前供应商折扣
                supplierDisc = GetSupplierDiscBySettingType(tttagKey, settingType, product.Supplier);
                if (supplierDisc != 0)
                    settingRate = settingRate * supplierDisc;
                //价格=全局，供应商，客户
                if (settingType == GoodsType.PrimeGolds || settingType == GoodsType.InlaySettings)
                {
                    product.GoldPrice = product.GoldPrice * settingRate;
                }
                else
                {
                    product.Price = product.Price * settingRate;
                }
            }
            return product;
        }
        private static decimal GetSupplierDiscBySettingType(string tttagKey, int lib, string supplier)
        {
            decimal supplierDisc = 1;
            //获取当前供应商折扣
            switch (lib)
            {
                case GoodsType.Diamond:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).Rebate ?? 1; break;
                case GoodsType.Ring:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).RingRebate ?? 1; break;
                case GoodsType.Parcel:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).ParcelRebate ?? 1; break;
                case GoodsType.Gem:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).GemRebate ?? 1; break;
                case GoodsType.Emerald:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).EmeraldRebate ?? 1; break;
                case GoodsType.PrimeGolds:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).PrimeGoldRebate ?? 1; break;
                case GoodsType.InlaySettings:
                    supplierDisc = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, supplier).InlaySettingsRebate ?? 1; break;
            }
            supplierDisc = supplierDisc == 0 ? 1 : supplierDisc;
            return supplierDisc;
        }
        ///// <summary>
        ///// 客户对应的产品折扣
        ///// </summary>
        ///// <param name="lib"></param>
        ///// <param name="param"></param>
        ///// <returns></returns>
        //private static decimal GetCustomerDiscBySettingType(GoodsType lib, HashParam param)
        //{
        //    CustomerInfo customerInfo = new CustomerInfo();
        //    decimal customerDisc = 1;
        //    if (param.ContainsKey("CustomerID"))//客户折扣
        //    {
        //        customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(Convert.ToInt32(param["CustomerID"]));
        //        switch (lib)
        //        {
        //            case GoodsType.stock:
        //                customerDisc = customerInfo.Rebate ?? 1; break;
        //            case GoodsType.ring:
        //                customerDisc = customerInfo.RingRebate ?? 1; break;
        //            case GoodsType.parcel:
        //                customerDisc = customerInfo.ParcelRebate ?? 1; break;
        //            case GoodsType.gem:
        //                customerDisc = customerInfo.GemRebate ?? 1; break;
        //            case GoodsType.emerald:
        //                customerDisc = customerInfo.EmeraldRebate ?? 1; break;
        //            case GoodsType.primeGolds:
        //                customerDisc = customerInfo.PrimeGoldRebate ?? 1; break;
        //        }
        //    }
        //    else
        //    {
        //        Logger.Error(typeof(Wholesaler), "GetCustomerDiscBySettingType,没有客户ID");
        //    }
        //    return customerDisc;
        //}
        //修改统包
        public string ModParcel(string modParcelsParam)
        {
            logParam = modParcelsParam;
            string tttagKey = CommonUrl.getURL(null, modParcelsParam);
            Parcels parcel = Json.Deserialize<Parcels>(modParcelsParam);
            return CRetails.AllProduct(tttagKey, modParcelsParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, parcel.ID), "put");
        }
        //添加统包
        public string AddParcel(string modParcelsParam)
        {
            logParam = modParcelsParam;
            string tttagKey = CommonUrl.getURL(null, modParcelsParam);
            Parcels parcel = Json.Deserialize<Parcels>(modParcelsParam);
            return CRetails.AllProduct(tttagKey, modParcelsParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, ""), "post");
        }
        //删除统包
        public string DeleteParcel(string delParcelsParam)
        {
            logParam = delParcelsParam;
            string tttagKey = CommonUrl.getURL(null, delParcelsParam);
            Parcels parcel = Json.Deserialize<Parcels>(delParcelsParam);
            return CRetails.AllProduct(tttagKey, delParcelsParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, parcel.ID), "delete");
        }


        /// <summary>
        /// 移除购物车
        /// </summary>
        /// <param name="ringCartId"></param>
        /// <returns></returns>
        public string RemoveParcelsCart(string removeFromCartParam)
        {
            return DelAllCartByCustomerIdAndProductIds(removeFromCartParam, "ParcelIDs", "Parcel_Cart.DeleteByParcelIDs");
        }

        //删除作废订单
        public string ParcelDelOrders(string delOrdersParam)
        {
            logParam = delOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            delOrdersResult = trans_delOrders.Delete("ParcelOrder.DelOrders", _orderIDs[i]);//删除结果
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }


        #endregion
        #region 客户相关
        /// <summary>
        /// 所有客户 9-6
        /// </summary>
        /// <param name="getCustomersParam"></param>
        /// <returns></returns>
        public string GetCustomerList(string strParam)
        {
            return CRetails.GetCustomerList(strParam);
        }
        /// <summary>
        /// 客户列表------ 纯粹读数据 无需 事务
        /// </summary>
        /// <param name="getOrdersParam"></param>
        /// <returns></returns>
        public string GetCustomers(string getCustomersParam)
        {
            logParam = getCustomersParam;
            HashParam param = Json.Deserialize<HashParam>(getCustomersParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getCustomersParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                PageList<CustomerInfo> _customersInfo = YZ.GetDatabase(tttagKey).QueryForList<CustomerInfo>("Customer.GetList", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));//ToInt32 9-6
                if (_customersInfo != null && _customersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_customersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载客户列表失败，程序错误");
            }
        }

        public string GetCustomerInfo(string param)
        {
            try
            {
                logParam = param;
                string tttagKey = CommonUrl.getURL(null, param);
                Logger.Debug(this.GetType(), DateTime.Now + "GetCustomerInfo param:" + param);
                GetMethodInfoAndWriteLogs(null, param);
                HashParam hParam = JsonConvert.DeserializeObject<HashParam>(param);
                if (hParam.GetInt("CustomerID", 0) == 0)
                {
                    return CommonLog.MsgErrorInfo("没有找到对应参数");
                }
                else
                {
                    CustomerInfo customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerById", hParam);
                    if (customer != null)
                    {
                        return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(customer));
                    }
                    else
                        return CommonLog.MsgErrorInfo("没有找到对应参数客户");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("获取客户失败");
            }


        }
        /// <summary>
        /// 客户个数统计
        /// </summary>
        /// <returns></returns>
        public string CustomerNumber(string customerNumberParam)
        {
             logParam = customerNumberParam;
            HashParam param = Json.Deserialize<HashParam>(customerNumberParam);
            string tttagKey = CommonUrl.getURL(param, customerNumberParam);
            //templateJSON
            try
            {
                IList<CustomerStatusNum> _customerInfo = YZ.GetDatabase(tttagKey).QueryForList<CustomerStatusNum>("Customer.GetCustomerNumber", param);
                if (_customerInfo != null && _customerInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_customerInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("客户统计为0.");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("客户统计加载失败");
            }
        }
        public string AddCustomer(string param)
        {
            try
            {
                logParam = param;
                string tttagKey = CommonUrl.getURL(null, param);
                //GetMethodInfoAndWriteLogs(null, param);
                CustomerInfo customer = JsonConvert.DeserializeObject<CustomerInfo>(param);
                var dbCustomer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerByOpenid", customer.OpenId);
                var msg = "失败";
                bool isAdd = false;
                if (dbCustomer == null)
                {
                    isAdd = YZ.GetDatabase(tttagKey).Add(customer) > 0;
                    if (isAdd)
                    {
                        msg = "成功";
                    }
                }
                else
                {
                    isAdd = true;
                    msg = "成功";
                }
                return CommonLog.MsgInfo(isAdd, "添加客户" + msg);
            }
            catch (Exception ex)
            {

                Logger.Error(this.GetType(), string.Format("-AddCustomer param:{0}, 错误信息：{1}", param, ex.Message));
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("添加客户失败!" + ex.Message);
            }


        }
        /// <summary>
        /// (单个操作)修改客户（公司客户） --含事务
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public int GetCustomerIdByOpenid(string openid, string tttagKey)
        {
            int customerId = 0;
            var cacheKey = $"{tttagKey}_{openid}";
            if (HttpRuntime.Cache.Get(cacheKey) != null)
            {
                int.TryParse(HttpRuntime.Cache.Get(cacheKey).ToString(),out customerId);
            }
            else
            {
                var customerIDStr = YZ.GetDatabase(tttagKey).QueryForObject("Customer.GetCustomerIdByOpenid", openid);
                Logger.Debug(this.GetType(), DateTime.Now + "GetCustomerIdByOpenid customerID:" + customerIDStr);
                if (customerIDStr != null)
                {
                    var idStr = customerIDStr.ToString();
                    int.TryParse(idStr, out  customerId);
                    CommonClass.SetCache(cacheKey, idStr);
                }
              
            }
            return customerId;
        }
        /// <summary>
        /// (单个操作)修改客户（公司客户） --含事务
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public string EditCustomer(string editCustomerParam)
        {
            var logParam = editCustomerParam;
            HashParam hsParam = Json.Deserialize<HashParam>(editCustomerParam);
            string tttagKey = CommonUrl.getURL(hsParam, editCustomerParam, "编辑客户资料");
            CustomerInfo param = Json.Deserialize<CustomerInfo>(editCustomerParam);
            try
            {
                param.UpdateTime = DateTime.Now;
                if (hsParam.ContainsKey("UserName") && hsParam.ContainsKey("Mobile") && hsParam.ContainsKey("NickName"))
                //if (!string.IsNullOrEmpty(param.UserName) || !string.IsNullOrEmpty(param.Mobile) || !string.IsNullOrEmpty(param.NickName))
                {
                    param.UserName = param.UserName.Trim();
                    param.Mobile = param.Mobile.Trim();
                    param.NickName = param.NickName.Trim();
                    CustomerInfo customerResult = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.CheckCustomer", param);
                    if (customerResult != null)
                    {
                        return CommonLog.MsgErrorInfo("用户名，公司简称或电话已注册，请重新修改后保存");
                    }
                    //客户密码
                    if (param.UserPassword != null)
                    {
                        int CustomerID = param.CustomerID;//帐号
                        CustomerInfo customerInfo = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerById", CustomerID);//通过用户名UserName 
                        if (customerInfo != null)
                        {
                            if (!(customerInfo.UserPassword == param.UserPassword.ToString()))
                            {
                                param.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(param.UserPassword.ToString());
                            }
                        }
                    }
                }
                using (ITransaction trans_editCustomer = YZ.GetTransaction(tttagKey))
                {
                    //删除角色时有个sql  customer.xml 里面的ReplaceCustomerRole  如果不是最后加上,会多出很多逻辑判断，为了简单加上,
                    if (!string.IsNullOrEmpty(param.RoleNames))
                        param.RoleNames = param.RoleNames.TrimEnd(',') + ",";
                    else
                        param.RoleNames = "";
                    int editCustomerResult = trans_editCustomer.Edit(param);
                    if (editCustomerResult > 0)
                    {
                        try
                        {
                            trans_editCustomer.CommitTransaction();//提交事务
                            CommonLog.SendMQMsg(tttagKey, "编辑客户资料：修改成功" + editCustomerParam);
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        catch (Exception ex)
                        {
                            trans_editCustomer.RollBackTransaction();//回滚事务
                            CommonLog.SendMQMsg(tttagKey, "异常信息：编辑客户资料2" + ex.StackTrace + "参数:" + logParam);
                            return CommonLog.MsgErrorInfo("网络异常,请重试");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：编辑客户资料3" + ex.StackTrace + "参数:" + logParam);
                if (ex.Message.IndexOf("Duplicate entry") > -1)
                    return CommonLog.MsgErrorInfo("用户名已存在");
                return CommonLog.MsgErrorInfo("修改失败，程序错误");
            }
        }

        #endregion
        #region 团队业务相关
        /// <summary>
        /// 团队登录（公司员工）
        /// </summary>
        /// <param name="teamLoginParam"></param>
        /// <returns></returns>
        public string UserLogin(string userLoginParam)
        {
            logParam = userLoginParam;
            HashParam param = Json.Deserialize<HashParam>(userLoginParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, userLoginParam,"团队登陆");
            // userLoginParam 为 string name, string pwd ,string activeip
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"data\":#result}"; //templateJSON
            //string strCustomer = JsonConvert.SerializeObject(param);//将HashParam格式化为Json传给Android端  （Serialize 序列化）
            try
            {
                string _name = param.GetString("Name");//帐号
                string _pwd = param.GetString("Pwd");//密码
                //登录参数非空判断
                if (string.IsNullOrEmpty(_name) || string.IsNullOrEmpty(_pwd))
                {
                    return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:帐号或密码为空").Replace("#result", JsonConvert.SerializeObject(""));
                }
                //团队表user
                UserInfoRole userResult = YZ.GetDatabase(tttagKey).QueryForObject<UserInfoRole>("User.Login", _name);
                if (userResult != null)
                {
                    if (userResult.UserPassword.Equals(Yunzuan.Foundation.Safe.EncryptHelper.MD5(_pwd)))
                    {
                        ////团队帐号状态SysStatus（-1 已删除 0 已禁用 2 审核中 1正常）
                        //if (userResult.SysStatus.Value == -1)
                        //{
                        //    return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:帐号或密码不正确").Replace("#result", JsonConvert.SerializeObject(""));
                        //}
                        //if (userResult.SysStatus.Value == 0)
                        //{
                        //    return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:帐号或密码不正确").Replace("#result", JsonConvert.SerializeObject(""));
                        //}
                        //if (userResult.SysStatus.Value == 2)
                        //{
                        //    return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:帐号或密码不正确").Replace("#result", JsonConvert.SerializeObject(""));
                        //}
                        //if (userResult.SysStatus.Value == 1)
                        //{
                            try
                            {
                                //更新客户的登录次数LoginCount、上次活跃时间LastActiveTime 和 活跃IP
                                userResult.ActiveIP = param.GetString("ActiveIP");//活跃IP ActiveIP 11-18
                                int userLoginResult = YZ.GetDatabase(tttagKey).Update("User.LoginCount", userResult);
                                if (userLoginResult > 0)
                                {
                                    UserLoginLog userloginlog = new UserLoginLog();
                                    userloginlog.HttpURL = param.GetString("HttpURL");
                                    userloginlog.tttagKey = tttagKey;
                                    userloginlog.UserType = "1";//团队1，客户2
                                    userloginlog.LoginUserID = userResult.UserID.ToString();
                                    userloginlog.UserName = userResult.UserName;
                                    userloginlog.Pwd = _pwd;
                                    userloginlog.ActiveIP = param.GetString("ActiveIP"); 
                                    userloginlog.OprationDesc = "团队登陆";
                                    userloginlog.CreateDate = DateTime.Now;
                                    string strP = JsonConvert.SerializeObject(userloginlog);
                                    ConmonMQMsgClass.send("登陆" + strP);
                                    return _msgInfo.Replace("#code", "true").Replace("#msg", "团队登录成功").Replace("#result", JsonConvert.SerializeObject(userResult));
                                }
                                else
                                {
                                    return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:数据库更新操作错误，请重试").Replace("#result", JsonConvert.SerializeObject(""));
                                }
                            }
                            catch (Exception ex)
                            {
                                GetMethodInfoAndWriteLogs(ex);
                                return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败，程序错误").Replace("#result", ex.Message);
                            }
                        //}
                    }
                    else
                    {
                        return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:账号或密码错误").Replace("#result", JsonConvert.SerializeObject(""));
                    }
                }
                return _msgInfo.Replace("#code", "false").Replace("#msg", "团队登录失败:帐号或密码不正确").Replace("#result", JsonConvert.SerializeObject(""));
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("团队登录失败，"+ex.Message);
            }
        }
        /// <summary>
        /// (单个操作)添加团队（公司团队） --含事务
        /// </summary>
        /// <param name="addCustomerParam"></param>
        /// <returns></returns>
        public string AddUser(string addUserParam)
        {
            logParam = addUserParam;
            string tttagKey = CommonUrl.getURL(null, addUserParam);
            //UserPassword(必传)
            //templateJSON
            UserInfo param = Json.Deserialize<UserInfo>(addUserParam);
            try
            {
                param.CreateTime = DateTime.Now;//注册时间
                param.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(param.UserPassword.ToString());//MD5
                using (ITransaction trans_addUser = YZ.GetTransaction(tttagKey))
                {
                    int addUserResult = trans_addUser.Add(param);
                    if (addUserResult > 0)
                    {
                        try
                        {
                            trans_addUser.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("添加团队成功");
                        }
                        catch (Exception)
                        {
                            trans_addUser.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("添加团队失败,请重试");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加团队失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("添加团队失败，程序错误");
            }
        }
        /// <summary>
        /// (单个操作)修改团队（公司团队） --含事务
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public string EditUser(string editUserParam)
        {
            logParam = editUserParam;
            string tttagKey = CommonUrl.getURL(null, editUserParam);
            //CustomerID（必传）
            //templateJSON
            UserInfo param = Json.Deserialize<UserInfo>(editUserParam);
            try
            {
                param.UpdateTime = DateTime.Now;
                //客户密码
                if (param.UserPassword != null)
                {
                    param.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(param.UserPassword.ToString());
                }
                using (ITransaction trans_editUser = YZ.GetTransaction(tttagKey))
                {
                    int editUserResult = trans_editUser.Edit(param);
                    if (editUserResult > 0)
                    {
                        try
                        {
                            trans_editUser.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("修改团队成功");
                        }
                        catch (Exception)
                        {
                            trans_editUser.RollBackTransaction();//回滚事务
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改团队失败，团队标识不存在");
                    }
                    return CommonLog.MsgErrorInfo("修改团队失败,请重试");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改团队失败，程序错误");
            }
        }
        /// <summary>
        /// 团队修改密码 9-21
        /// </summary>
        /// <param name="customerModifyPasswordParam"></param>
        /// <returns></returns>
        public string TeamModifyPassword(string teamModifyPasswordParam)
        {
            logParam = teamModifyPasswordParam;
            HashParam param = Json.Deserialize<HashParam>(teamModifyPasswordParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, teamModifyPasswordParam);
            //团队标识、老密码、新密码
            //templateJSON
            try
            {
                int _userID = Convert.ToInt32(param.GetInt("UserID"));//团队标识(强制转换)
                string _oldPassword = param.GetString("OldUserPassword");//老密码
                string _newPassword = param.GetString("NewUserPassword");//新密码
                UserInfo user = new UserInfo();
                user.UserID = _userID;
                user = YZ.GetDatabase(tttagKey).Get<UserInfo>(user);
                if (user != null)
                {
                    //判断老密码是否输入正确
                    if (Yunzuan.Foundation.Safe.EncryptHelper.MD5(_oldPassword) != user.UserPassword)
                    {
                        return CommonLog.MsgErrorInfo("老密码错误");
                    }
                    else
                    {
                        //设置新密码
                        user.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(_newPassword);
                        int teamModifyPwdResult = YZ.GetDatabase(tttagKey).Edit(user);
                        if (teamModifyPwdResult > 0)
                        {
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("修改失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("团队不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 团队列表 --- -- 纯粹读数据 无需 事务
        /// </summary>
        /// <param name="getCustomersParam"></param>
        /// <returns></returns>
        public string GetUsers(string getUsersParam)
        {
            logParam = getUsersParam;
            HashParam param = Json.Deserialize<HashParam>(getUsersParam);
            string tttagKey = CommonUrl.getURL(param, getUsersParam);
            //参数可全空
            try
            {
                PageList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetList", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));//所有
                if (_usersInfo != null && _usersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载团队列表失败，程序错误");
            }
        }
        /// <summary>
        /// 所有业务 9-6
        /// </summary>
        /// <param name="getSalesParam"></param>
        /// <returns></returns>
        public string GetSaleList(string getSaleListParam)
        {
            logParam = getSaleListParam;
            HashParam param = Json.Deserialize<HashParam>(getSaleListParam);//10-28
            string tttagKey = CommonUrl.getURL(param, getSaleListParam);
            //参数可全空
            try
            {
                IList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetSales", param);//业务
                if (_usersInfo != null && _usersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 业务列表 RoleID = 3 (8-19)
        /// </summary>
        /// <param name="getUsersParam"></param>
        /// <returns></returns>
        public string GetSales(string getSalesParam)
        {
            logParam = getSalesParam;
            PageParam param = Json.Deserialize<PageParam>(getSalesParam);
            string tttagKey = CommonUrl.getURL(param, getSalesParam);
            //参数可全空
            try
            {
                PageList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetSales", param, param.PageSize, param.PageIndex);//业务
                if (_usersInfo != null && _usersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载业务列表失败，程序错误");
            }
        }
        /// <summary>
        /// 所有采购（业务+采购）
        /// </summary>
        /// <param name="getPurchasesParam"></param>
        /// <returns></returns>
        public string GetPurchaseList(string getPurchaseListParam)
        {
            logParam = getPurchaseListParam;
            HashParam param = Json.Deserialize<HashParam>(getPurchaseListParam);//10-28
            string tttagKey = CommonUrl.getURL(param, getPurchaseListParam);
            //参数可全空
            try
            {
                IList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetPurchases", param);//采购
                if (_usersInfo != null && _usersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 纯采购列表 9-26
        /// </summary>
        /// <param name="getPurchaseListParam"></param>
        /// <returns></returns>
        public string GetPurchasers(string getPurchasersParam)
        {
            logParam = getPurchasersParam;
            string tttagKey = CommonUrl.getURL(null, getPurchasersParam);
            //参数可全空
            try
            {
                IList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetPurchasers", null);//纯采购列表 9-26
                if (_usersInfo != null && _usersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载采购列表失败，程序错误");
            }
        }
        /// <summary>
        /// 采购列表 RoleID = 4 (8-19)
        /// </summary>
        /// <param name="getSalesParam"></param>
        /// <returns></returns>
        public string GetPurchases(string getPurchasesParam)
        {
            logParam = getPurchasesParam;
            PageParam param = Json.Deserialize<PageParam>(getPurchasesParam);
            string tttagKey = CommonUrl.getURL(param, getPurchasesParam);
            //参数可全空
            try
            {
                PageList<UserInfo> _usersInfo = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.GetPurchases", param, param.PageSize, param.PageIndex);//采购
                if (_usersInfo != null && _usersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_usersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载采购列表失败，程序错误");
            }
        }
        /// <summary>
        /// 客户注册是否存在（公司客户）
        /// </summary>
        /// <param name="customerRegIsExistParam"></param>
        /// <returns></returns>
        public string CustomerRegIsExist(string customerRegIsExistParam)
        {
            return CWholesalers.CustomerRegIsExist(customerRegIsExistParam);
        }
        /// <summary>
        /// 审核客户 从待审核2到正常1
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public string ActiveCustomer(string activeCustomerParam)
        {
            var logParam = activeCustomerParam;
            string tttagKey = CommonUrl.getURL(null, activeCustomerParam, "审核客户账号");
            //CustomerID（必传）
            //templateJSON
            CustomerInfo param = Json.Deserialize<CustomerInfo>(activeCustomerParam);
            try
            {
                param.UserName = param.UserName.Trim();
                param.Mobile = param.Mobile.Trim();
                param.NickName = param.NickName.Trim();
                CustomerInfo customerResult = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.CheckCustomer", param);
                if (customerResult != null)
                {
                    return CommonLog.MsgErrorInfo("用户名，公司简称或电话已注册，请重新修改后保存");
                }
                param.UpdateTime = DateTime.Now;//01-11
                using (ITransaction trans_activeCustomer = YZ.GetTransaction(tttagKey))
                {
                    int activeCustomerResult = trans_activeCustomer.Edit(param);
                    if (activeCustomerResult > 0)
                    {
                        try
                        {
                            trans_activeCustomer.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                            //"客户帐号审核通过"短信提醒 8-30
                            #region
                            if (HttpContext.Current.Cache.Get(param.Mobile + "smsCacheParam" + tttagKey) == null && AllPublic.IsPhoneNo(param.Mobile))
                            {
                                //sms
                                HashParam hsParam = new HashParam();
                                //hsParam["customer"] = param.RealName;//名字
                                //hsParam["customer"] = param.NickName;//昵称
                                hsParam["customer"] = AllPublic.getSmsName(param.UserName);  //+":"+ param.NickName;//用户名和昵称 8-31
                                SMSManager.SendSms(param.Mobile, SMSLib.SMSTemplateByReview, hsParam);
                                HttpContext.Current.Cache.Insert(param.Mobile + "smsCacheParam" + tttagKey, param.Mobile);
                            }
                            #endregion
                            CommonLog.SendMQMsg(tttagKey, "审核成功");
                            return CommonLog.MsgSuccessInfo("审核成功");
                        }
                        catch (Exception e)
                        {
                            trans_activeCustomer.RollBackTransaction();//回滚事务
                            CommonLog.SendMQMsg(tttagKey, "异常信息：审核客户账号1" + activeCustomerParam);
                            return CommonLog.MsgErrorInfo("审核失败");
                        }
                    }
                    else
                    {
                        CommonLog.SendMQMsg(tttagKey, "异常信息：审核客户账号2" + activeCustomerParam);
                        return CommonLog.MsgErrorInfo("审核失败，客户标识不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.SendMQMsg(tttagKey, "异常信息：审核客户账号3" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("审核失败，程序错误");
            }
        }
        /// <summary>
        /// 团队添加是否存在（公司团队）
        /// </summary>
        /// <param name="customerRegIsExistParam"></param>
        /// <returns></returns>
        public string UserRegIsExist(string userRegIsExistParam)
        {
            logParam = userRegIsExistParam;
            HashParam param = Json.Deserialize<HashParam>(userRegIsExistParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, userRegIsExistParam);
            //判断团队帐号 、手机号是否已存在
            //templateJSON
            try
            {
                string _username = param.GetString("UserName").ToLower();//帐号转小写
                string _mobile = param.GetString("Mobile");//手机号
                if (!string.IsNullOrEmpty(_username) || !string.IsNullOrEmpty(_mobile))
                {
                    UserInfo userResult = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.RegIsExist", param);
                    if (userResult != null)
                    {
                        if (userResult.UserName.Equals(_username))
                        {
                            return CommonLog.MsgErrorInfo("已存在");
                        }
                        else if (userResult.Mobile.Equals(_mobile))
                        {
                            return CommonLog.MsgErrorInfo("已存在");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgSuccessInfo("可以注册");
                    }
                }
                return CommonLog.MsgErrorInfo("无法验证，帐号和手机号都为空");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("服务器错误");
            }
        }
        /// <summary>
        /// 获取单个员工资料（公司员工)
        /// </summary>
        /// <param name="customerInfoParam"></param>
        /// <returns></returns>
        public string GetUserInfo(string userInfoParam)
        {
            logParam = userInfoParam;
            string tttagKey = CommonUrl.getURL(null, userInfoParam);
            //templateJSON
            try
            {
                UserInfo param = Json.Deserialize<UserInfo>(userInfoParam); //解析Android传过来的Json   //Deserialize 反序列化
                UserInfo user = YZ.GetDatabase(tttagKey).Get<UserInfo>(param);
                if (user != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(user));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取团队资料失败，请检查团队标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误：");
            }
        }
        #endregion 业务相关end
        #region 财务相关
        /// <summary>
        /// 银行账户列表 12-8
        /// </summary>
        /// <param name="getFlowsParam"></param>
        /// <returns></returns>
        public string GetBanks(string getBanksParam)
        {
            logParam = getBanksParam;
            HashParam param = Json.Deserialize<HashParam>(getBanksParam);
            string tttagKey = CommonUrl.getURL(param, getBanksParam);
            //
            try
            {
                PageList<BankInfo> _banksInfo = YZ.GetDatabase(tttagKey).QueryForList<BankInfo>("Bank.GetBanks", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));
                if (_banksInfo != null && _banksInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_banksInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败");
            }
        }
        /// <summary>
        /// 银行账户列表 12-21
        /// </summary>
        /// <param name="getBankListParam"></param>
        /// <returns></returns>
        public string GetBankList(string getBankListParam)
        {
            logParam = getBankListParam;
            HashParam param = Json.Deserialize<HashParam>(getBankListParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getBankListParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                IList<BankInfo> _banks = YZ.GetDatabase(tttagKey).QueryForList<BankInfo>("Bank.GetBankList", param);//ToInt32 9-6
                if (_banks != null && _banks.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_banks));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败，程序错误");
            }
        }
        /// <summary>
        /// 银行账户
        /// </summary>
        /// <param name="getBankParam"></param>
        /// <returns></returns>
        public string GetBank(string getBankParam)
        {
            logParam = getBankParam;
            string tttagKey = CommonUrl.getURL(null, getBankParam);
            try
            {
                BankInfo param = Json.Deserialize<BankInfo>(getBankParam);
                BankInfo _bank = YZ.GetDatabase(tttagKey).Get<BankInfo>(param);
                if (_bank != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_bank));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取失败，请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误：");
            }
        }
        /// <summary>
        /// 添加账户
        /// </summary>
        /// <param name="addBankParam"></param>
        /// <returns></returns>
        public string AddBank(string addBankParam)
        {
            logParam = addBankParam;
            string tttagKey = CommonUrl.getURL(null, addBankParam);
            //templateJSON
            BankInfo param = Json.Deserialize<BankInfo>(addBankParam);
            try
            {
                param.CreateTime = DateTime.Now;
                using (ITransaction trans_addBank = YZ.GetTransaction(tttagKey))
                {
                    int addBankResult = trans_addBank.Add(param);
                    if (addBankResult > 0)
                    {
                        try
                        {
                            trans_addBank.CommitTransaction();//提交事务
                            return CommonLog.MsgSuccessInfo("添加成功");
                        }
                        catch (Exception)
                        {
                            trans_addBank.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("添加失败,请重试");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 修改银行账户 12-13
        /// </summary>
        /// <param name="editBankParam"></param>
        /// <returns></returns>
        public string EditBank(string editBankParam)
        {
            return AllPublic.EditBank(editBankParam);
        }
        /// <summary>
        /// 流水列表 12-3
        /// </summary>
        /// <param name="getAccountsParam"></param>
        /// <returns></returns>
        public string GetFlows(string getFlowsParam)
        {
            logParam = getFlowsParam;
            HashParam param = Json.Deserialize<HashParam>(getFlowsParam);
            string tttagKey = CommonUrl.getURL(null, getFlowsParam);
            //
            try
            {
                PageList<FlowResult> _flowsInfo = YZ.GetDatabase(tttagKey).QueryForList<FlowResult>("Flow.GetFlows", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));
                if (_flowsInfo != null && _flowsInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_flowsInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败");
            }
        }
        /// <summary>
        /// 账户转出
        /// </summary>
        /// <param name="bankTransferParam"></param>
        /// <returns></returns>
        public string BankTransfer(string bankTransferParam)
        {
            logParam = bankTransferParam;
            HashParam param = Json.Deserialize<HashParam>(bankTransferParam);
            string tttagKey = CommonUrl.getURL(param, bankTransferParam);
            //templateJSON
            try
            {
                if (!(param.GetDecimal("ExAmount") > 0))
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("转出金额必须大于0");
                }
                if (param.GetInt("ExBankID") == param.GetInt("BankID"))
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("转出和转入账户不能为同一账户");
                }
                //1.更新支出账户结余-支出(ExBankID)
                BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("ExBankID"));
                #region
                if (_bank != null)
                {
                    if (_bank.CheckResult == 0)
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("转出账户对账不符，请先对账");
                    }
                    BankInfo _bankInfo = new BankInfo();
                    _bankInfo.BankID = _bank.BankID;//支出账户
                    _bankInfo.UpdateTime = DateTime.Now;
                    //ExAmount 实支付金额
                    if ((_bank.BankBalance + (-param.GetDecimal("ExAmount"))) >= 0)
                    {
                        //支出账户能够支付实支出金额
                        _bankInfo.BankBalance = _bank.BankBalance + (-param.GetDecimal("ExAmount"));//实支出金额
                    }
                    else
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("转出账户结余不足,请先入账");
                    }
                    using (ITransaction trans_banktransfer = YZ.GetTransaction(tttagKey))
                    {
                        int editBankBalanceResult = trans_banktransfer.Edit(_bankInfo);//更新账户结余 -只能用Edit
                        if (editBankBalanceResult > 0)
                        {
                            //2.添加支出已审核记录
                            #region
                            FlowInfo _flowInfo = new FlowInfo();
                            _flowInfo.Account = _bankInfo.BankID;
                            _flowInfo.Amount = param.GetDecimal("ExAmount");//实支出
                            _flowInfo.Balance = _bankInfo.BankBalance;
                            _flowInfo.Currency = _bank.Currency;//1人民币 2美金
                            _flowInfo.Status = 1;//1已审核
                            _flowInfo.Type = 2;//2支出
                            _flowInfo.ApplyID = param.GetInt("UserID");
                            _flowInfo.ReviewID = param.GetInt("UserID");
                            _flowInfo.Comments = param.GetString("Comments");
                            _flowInfo.ArrivalTime = param.GetDataTime("ArrivalTime");//到账日期
                            _flowInfo.Remarks = "账户转账";
                            _flowInfo.Abstract = 11;//11 账户转账
                            _flowInfo.CreateTime = DateTime.Now;
                            _flowInfo.UpdateTime = DateTime.Now;
                            int addFlowResult = trans_banktransfer.Add(_flowInfo);
                            if (addFlowResult > 0)
                            {
                                //更新RMB-收入账户结余BankID
                                #region
                                BankInfo _expensebank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("BankID"));
                                if (_expensebank != null)
                                {
                                    if (_expensebank.CheckResult == 0)
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("转入账户对账不符，请先对账");
                                    }
                                    BankInfo _expenseBankInfo = new BankInfo();
                                    _expenseBankInfo.BankID = _expensebank.BankID;//转入账户
                                    _expenseBankInfo.BankBalance = _expensebank.BankBalance + param.GetDecimal("ExAmount");
                                    _expenseBankInfo.UpdateTime = DateTime.Now;
                                    int editexpenseBankBalanceResult = trans_banktransfer.Edit(_expenseBankInfo);//更新账户结余 -只能用Edit
                                    if (editexpenseBankBalanceResult > 0)
                                    {
                                        //添加流水记录
                                        #region
                                        FlowInfo _expflowInfo = new FlowInfo();
                                        _expflowInfo.Account = _expensebank.BankID;
                                        _expflowInfo.Amount = param.GetDecimal("ExAmount");
                                        _expflowInfo.Balance = _expensebank.BankBalance + param.GetDecimal("ExAmount");
                                        _expflowInfo.Currency = _expensebank.Currency;//1人民币 2美金
                                        _expflowInfo.Status = 1;//1已审核
                                        _expflowInfo.Type = 1;//1收入                                        
                                        _expflowInfo.ApplyID = param.GetInt("UserID");
                                        _expflowInfo.ReviewID = param.GetInt("UserID");
                                        _expflowInfo.Comments = param.GetString("Comments");
                                        _expflowInfo.ArrivalTime = param.GetDataTime("ArrivalTime");//到账日期
                                        _expflowInfo.Remarks = "账户转账";
                                        _expflowInfo.Abstract = 11;//11 账户转账
                                        _expflowInfo.CreateTime = DateTime.Now;
                                        _expflowInfo.UpdateTime = DateTime.Now;
                                        int addExpFlowResult = trans_banktransfer.Add(_expflowInfo);
                                        if (addExpFlowResult > 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("添加支出流水失败");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("更新账户结余失败");
                                    }
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("转入账户不存在,请检查标识");
                                }
                                #endregion
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("添加支出流水失败");
                            }
                            #endregion
                        }
                        else
                        {
                            //跳出
                            return CommonLog.MsgErrorInfo("更新账户结余失败");
                        }
                        //事务
                        try
                        {
                            //提交事务
                            trans_banktransfer.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("转出成功");
                        }
                        catch (Exception)
                        {
                            //回滚事务
                            trans_banktransfer.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("转出失败");
                        }
                    }
                }
                else
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("转出账户不存在,请检查标识");
                }
                #endregion
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 直接账户充值 01-05
        /// </summary>
        /// <param name="directChargeParam"></param>
        /// <returns></returns>
        public string DirectCharge(string directChargeParam)
        {
            logParam = directChargeParam;
            HashParam param = Json.Deserialize<HashParam>(directChargeParam);
            string tttagKey = CommonUrl.getURL(param, directChargeParam);
            //templateJSON
            try
            {
                //1更新货款账户结余 + Type=1
                BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("BankID"));
                if (_bank != null)
                {
                    if (_bank.CheckResult > 0)
                    {
                        BankInfo _bankInfo = new BankInfo();
                        _bankInfo.BankID = _bank.BankID;//充值收入账户
                        _bankInfo.UpdateTime = DateTime.Now;
                        if (param.GetDecimal("Amount") > 0)
                        {
                            _bankInfo.BankBalance = _bank.BankBalance + param.GetDecimal("Amount");//充值金额
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败，充值金额应大于0");//跳出
                        }
                        using (ITransaction trans_modBankBalance = YZ.GetTransaction(tttagKey))
                        {
                            int editBankBalanceResult = trans_modBankBalance.Edit(_bankInfo);//更新收入账户结余
                            if (editBankBalanceResult > 0)
                            {
                                //2添加已审核收入流水
                                FlowInfo _flowInfo = new FlowInfo();
                                _flowInfo.Account = _bankInfo.BankID;
                                _flowInfo.Amount = param.GetDecimal("Amount");//充值金额
                                _flowInfo.Balance = _bankInfo.BankBalance;
                                _flowInfo.Currency = param.GetShort("Currency");//币种
                                _flowInfo.Status = 1;//1已审核
                                _flowInfo.Type = 1;//1收入
                                _flowInfo.ApplyID = param.GetInt("UserID");
                                _flowInfo.ReviewID = param.GetInt("UserID");
                                _flowInfo.Purpose = param.GetShort("Purpose");//用途
                                _flowInfo.Others = param.GetString("Others");
                                _flowInfo.Currency = _bank.Currency;//币种
                                _flowInfo.Remarks = "直接充值";
                                _flowInfo.Comments = param.GetString("Comments");
                                _flowInfo.Abstract = 10;//10 直接充值
                                _flowInfo.CreateTime = DateTime.Now;
                                _flowInfo.UpdateTime = DateTime.Now;
                                int addFlowResult = trans_modBankBalance.Add(_flowInfo);
                                if (addFlowResult > 0)
                                {
                                    //3更新支出账户结余 - Type=2
                                    BankInfo _exbank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByType", 2);//核心Type=2
                                    if (_exbank != null)
                                    {
                                        if (_exbank.CheckResult > 0)
                                        {
                                            BankInfo _exbankInfo = new BankInfo();
                                            _exbankInfo.BankID = _exbank.BankID;//充值支出账户
                                            _exbankInfo.UpdateTime = DateTime.Now;
                                            _exbankInfo.BankBalance = _exbank.BankBalance + (-param.GetDecimal("Amount"));//充值支出金额
                                            int editExBankBalanceResult = trans_modBankBalance.Edit(_exbankInfo);//更新支出账户结余
                                            if (editExBankBalanceResult > 0)
                                            {
                                                //2添加已审核收入流水
                                                FlowInfo _exflowInfo = new FlowInfo();
                                                _exflowInfo.Account = _exbankInfo.BankID;
                                                _exflowInfo.Amount = param.GetDecimal("Amount");//充值金额
                                                _exflowInfo.Balance = _exbankInfo.BankBalance;
                                                _exflowInfo.Currency = param.GetShort("Currency");//币种
                                                _exflowInfo.Status = 1;//1已审核
                                                _exflowInfo.Type = 2;//2支出
                                                _exflowInfo.ApplyID = param.GetInt("UserID");
                                                _exflowInfo.ReviewID = param.GetInt("UserID");
                                                _exflowInfo.Purpose = param.GetShort("Purpose");//用途
                                                _exflowInfo.Others = param.GetString("Others");
                                                _exflowInfo.Currency = _exbank.Currency;//币种
                                                _exflowInfo.Remarks = "直接充值";
                                                _exflowInfo.Comments = param.GetString("Comments");
                                                _exflowInfo.Abstract = 10;//10 直接充值
                                                _exflowInfo.CreateTime = DateTime.Now;
                                                _exflowInfo.UpdateTime = DateTime.Now;
                                                int addExFlowResult = trans_modBankBalance.Add(_exflowInfo);
                                                if (addExFlowResult > 0)
                                                {
                                                    //继续
                                                }
                                                else
                                                {
                                                    return CommonLog.MsgErrorInfo("失败，添加支出记录失败");//跳出
                                                }
                                            }
                                            else
                                            {
                                                return CommonLog.MsgErrorInfo("失败，更新账户结余失败");//跳出
                                            }
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("支出账户对账不符，请先对账");//跳出
                                        }
                                    }
                                    else
                                    {
                                        //无Type=2账户(美金支出账户)
                                    }
                                }
                                else
                                {
                                    return CommonLog.MsgErrorInfo("失败，添加收入记录失败");//跳出
                                }
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("失败，更新账户结余失败");//跳出
                            }
                            //事务
                            #region
                            try
                            {
                                //提交事务
                                trans_modBankBalance.CommitTransaction();
                                return CommonLog.MsgSuccessInfo("充值成功");
                            }
                            catch (Exception)
                            {
                                //回滚事务
                                trans_modBankBalance.RollBackTransaction();
                                return CommonLog.MsgErrorInfo("充值失败");
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("收入账户对账不符，请先对账");//跳出
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("账户不存在,请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 客户充值 (0申请充值 1直接充值)
        /// </summary>
        /// <param name="addChargeParam"></param>
        /// <returns></returns>
        public string AddCharge(string addChargeParam)
        {
            logParam = addChargeParam;
            string tttagKey = CommonUrl.getURL(null, addChargeParam);
            //templateJSON
            RechargeInfo param = Json.Deserialize<RechargeInfo>(addChargeParam);
            try
            {
                CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", param.customer_id);//单个客户信息，通过CustomerID
                if (_customerInfo != null)
                {
                    param.CreateTime = DateTime.Now;//记录时间
                    param.sale_id = _customerInfo.SalesUserID;//业务             
                    //1 直接充值
                    if (param.OperationModel == 1)
                    {
                        param.UpdateTime = DateTime.Now;//审核时间
                    }
                    using (ITransaction trans_addCharge = YZ.GetTransaction(tttagKey))
                    {
                        int addChargeResult = trans_addCharge.Add(param);
                        if (addChargeResult > 0)
                        {
                            //直接充值1，更新客户余额(客户更新前余额+本次充值金额)
                            if (param.OperationModel == 1)
                            {
                                _customerInfo.Balance = param.AmountOfMoney.Value;//本次充值金额
                                using (ITransaction trans_editBalance = YZ.GetTransaction(tttagKey))
                                {
                                    int editBalanceResult = trans_editBalance.Update("Customer.EditBalance", _customerInfo);//客户余额更新结果
                                    if (editBalanceResult > 0)
                                    {
                                        try
                                        {
                                            trans_editBalance.CommitTransaction(); //触发入库事务
                                        }
                                        catch (Exception)
                                        {
                                            trans_editBalance.RollBackTransaction();//回滚事务
                                        }
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo("直接充值失败,无法更新客户余额");
                                    }
                                }
                            }
                            try
                            {
                                trans_addCharge.CommitTransaction(); //提交事务
                                return CommonLog.MsgSuccessInfo("处理成功");
                            }
                            catch (Exception e)
                            {
                                trans_addCharge.RollBackTransaction();//回滚事务
                                return CommonLog.MsgErrorInfo("处理失败");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("处理失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("处理失败,客户不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("处理失败");
            }
        }
        /// <summary>
        /// 获取单条记账明细
        /// </summary>
        /// <returns></returns>
        public string GetChargeInfo(string chargeInfoParam)
        {
            logParam = chargeInfoParam;
            string tttagKey = CommonUrl.getURL(null, chargeInfoParam);
            //templateJSON
            RechargeInfo param = Json.Deserialize<RechargeInfo>(chargeInfoParam); //解析Android传过来的Json   //Deserialize 反序列化
            try
            {
                RechargeInfo chargeInfo = YZ.GetDatabase(tttagKey).Get<RechargeInfo>(param);
                if (chargeInfo != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(chargeInfo));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取记账明细失败，请检查明细标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 客户充值（1直接充值 -1 作废充值）
        /// </summary>
        /// <param name="editChargeParam"></param>
        /// <returns></returns>
        public string EditCharge(string editChargeParam)
        {
            logParam = editChargeParam;
            string tttagKey = CommonUrl.getURL(null, editChargeParam);
            //id（必传）
            //templateJSON
            RechargeResult param = Json.Deserialize<RechargeResult>(editChargeParam);
            try
            {
                CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerInfo", param.customer_id);//单个客户信息，通过CustomerID
                if (_customerInfo != null)
                {
                    param.UpdateTime = DateTime.Now;
                    using (ITransaction trans_editCharge = YZ.GetTransaction(tttagKey))
                    {
                        int editChargeResult = trans_editCharge.Edit(param);
                        if (editChargeResult > 0)
                        {
                            //直接充值1，更新客户余额(客户更新前余额+本次充值金额)
                            if (param.OperationModel == 1)
                            {
                                _customerInfo.Balance = param.AmountOfMoney.Value;//本次充值金额
                                using (ITransaction trans_editBalance = YZ.GetTransaction(tttagKey))
                                {
                                    int editBalanceResult = trans_editBalance.Update("Customer.EditBalance", _customerInfo);//客户余额更新结果
                                    if (editBalanceResult > 0)
                                    {
                                        try
                                        {
                                            trans_editBalance.CommitTransaction(); //触发入库事务
                                        }
                                        catch (Exception)
                                        {
                                            trans_editBalance.RollBackTransaction();//回滚事务
                                        }
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo("处理失败:更新客户余额失败");
                                    }
                                }
                            }
                            try
                            {
                                trans_editCharge.CommitTransaction();
                                return CommonLog.MsgSuccessInfo("处理成功");
                            }
                            catch (Exception e)
                            {
                                trans_editCharge.RollBackTransaction();
                                return CommonLog.MsgErrorInfo("处理失败");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("处理失败:标识不存在");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("处理失败:客户不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("处理失败，程序错误");
            }
        }
        /// <summary>
        /// 流水订单详情
        /// </summary>
        /// <returns></returns>
        public string GetOrderIDsDetail(string orderIDsParam)
        {
            logParam = orderIDsParam;
            HashParam param = Json.Deserialize<HashParam>(orderIDsParam);
            string tttagKey = CommonUrl.getURL(param, orderIDsParam);
            //templateJSON
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                    if (OrderList != null && OrderList.Count > 0)
                    {
                        return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(OrderList));//Serialize 序列化
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("没有任何记录");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 客户充值
        /// </summary>
        /// <returns></returns>
        public string GetCharges(string getChargesParam)
        {
            logParam = getChargesParam;
            HashParam param = Json.Deserialize<HashParam>(getChargesParam);
            string tttagKey = CommonUrl.getURL(param, getChargesParam);
            //
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"totalrmb\":#rmb}";
            //统计
            decimal? TotalRMB = 0;//总人民币 9-22
            try
            {
                PageList<RechargeResult> _chargesInfo = YZ.GetDatabase(tttagKey).QueryForList<RechargeResult>("Recharge.GetCharges", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));
                if (_chargesInfo != null && _chargesInfo.Data.Count > 0)
                {
                    for (int i = 0; i < _chargesInfo.Data.Count; i++)
                    {
                        TotalRMB += _chargesInfo.Data[i].AmountOfMoney;
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", JsonConvert.SerializeObject(_chargesInfo)).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB));
                }
                else
                {
                    //空
                    return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("没有任何记录")).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败");
            }
        }
        /// <summary>
        /// 导出充值记录 12-3
        /// </summary>
        /// <param name="exportChargesParam"></param>
        /// <returns></returns>
        public string ExportCharges(string exportChargesParam)
        {
            logParam = exportChargesParam;
            HashParam param = Json.Deserialize<HashParam>(exportChargesParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, exportChargesParam);
            string FileName = "充值 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<RechargeResult> ChargeList = YZ.GetDatabase(tttagKey).QueryForList<RechargeResult>("Recharge.GetCharges", param);//订单IList
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>名字</td>");
                OutFileContent.Append("<td>业务</td>");
                OutFileContent.Append("<td>金额</td>");
                OutFileContent.Append("<td>账户</td>");
                OutFileContent.Append("<td>类型</td>");
                OutFileContent.Append("<td>到账时间</td>");
                OutFileContent.Append("<td>备注</td>");
                OutFileContent.Append("<td>操作人</td>");
                OutFileContent.Append("<td>申请时间</td>");
                OutFileContent.Append("<td>审核时间</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (ChargeList != null && ChargeList.Count > 0)
                {
                    for (int i = 0; i < ChargeList.Count; i++)
                    {
                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].CustomerNickName + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].CustomerRealName + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].UserRealName + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].AmountOfMoney + "</td>");
                        columnValue.Append("<td>" + PaymentModelFormat(ChargeList[i].PaymentModel) + "</td>");
                        columnValue.Append("<td>" + OperationModelFormat(ChargeList[i].OperationModel) + "</td>");//12-3
                        columnValue.Append("<td>" + ChargeList[i].AdddateTime + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].Remarks + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].Creator + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].CreateTime + "</td>");
                        columnValue.Append("<td>" + ChargeList[i].UpdateTime + "</td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + ChargeList.Count + "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    //返回文件下载地址 http://localhost:3952/excel/xx.xls
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出充值失败:");
            }
        }
        /// <summary>
        /// 客户消费
        /// </summary>
        /// <param name="getChargesParam"></param>
        /// <returns></returns>
        public string GetPays(string getPaysParam)
        {
            logParam = getPaysParam;
            HashParam param = Json.Deserialize<HashParam>(getPaysParam);//9-6
            string tttagKey = CommonUrl.getURL(param, getPaysParam);
            try
            {
                //统计
                decimal? TotalRMB = 0;//总人民币 9-22
                PageList<OrderInfoResult> _paysInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetPays", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));
                if (_paysInfo != null && _paysInfo.Data.Count > 0)
                {
                    for (int i = 0; i < _paysInfo.Data.Count; i++)
                    {
                        TotalRMB += _paysInfo.Data[i].ConfirmPrice;
                    }
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_paysInfo)).Replace("#rmb", JsonConvert.SerializeObject(TotalRMB));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败");
            }
        }
        //发送验证码 注册 
        public string ValidateCode(string param)
        {
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(param);
            if (_param.ContainsKey("Tel"))
            {
                var tel = _param["Tel"].ToString();
                //session["smsCode"]  20
                var msg = SMSManager.SendSms(tel, SMSLib.SMSTemplateByReg, _param);
                if (msg.Contains("<success>true</success>"))
                {
                    return CommonLog.MsgSuccessInfo("发送成功");
                }
                else
                {
                    if (msg.Contains("触发分钟级流"))
                    {
                        return CommonLog.MsgErrorInfo("发送失败,info:发送短信太频繁");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("发送失败,info:" + Regex.Replace(msg, "<[^>]*>", "").Replace("\n", "").Replace("\r", ""));
                    }
                }
            }
            else
            {
                return CommonLog.MsgErrorInfo("发送失败");
            }
            //客户
        }

        public string BindOnAccount(string param)
        {
            try
            {
                logParam = param;
                HashParam customer = JsonConvert.DeserializeObject<HashParam>(param);
                string tttagKey = CommonUrl.getURL(customer, param);
                //openid | ID
                if (customer.ContainsKey("CustomerID") && customer.ContainsKey("Tel") && customer.ContainsKey("smsCode"))
                {
                    //wx
                    var customerId = Convert.ToInt32(customer["CustomerID"]); //微信的id
                    var wxCustomer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(customerId); // 
                    if (wxCustomer != null)
                    {
                        try
                        {
                            var cacheKey = "Cache:smsCode" + customer.GetString("Tel");
                            //验证验证码是否正确
                            if (HttpRuntime.Cache.Get(cacheKey) != null && HttpRuntime.Cache.Get(cacheKey).ToString().ToLower() == customer.GetString("smsCode").ToString().ToLower())
                            {
                            }
                            if (string.IsNullOrEmpty(wxCustomer.Mobile) && string.IsNullOrEmpty(wxCustomer.UserPassword))
                            {
                                //验证账号密码是否正确
                                var pwd = Yunzuan.Foundation.Safe.EncryptHelper.MD5(customer["Pwd"].ToString());
                                var tel = customer["Tel"].ToString();
                                customer["Pwd"] = pwd;

                                //Logger.Info(this.GetType(), logTemplate + "-记录信息：" + msg);
                                var webCustomer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerByTelAndPwd", customer);
                                if (webCustomer != null)
                                {
                                    if (string.IsNullOrEmpty(webCustomer.OpenId))
                                    {
                                        //执行存储过程
                                        string msg = ExceProcedure(wxCustomer.CustomerID, tel, pwd);
                                        if (msg == "")
                                            return CommonLog.MsgSuccessInfo("绑定账号成功！");
                                        else
                                            return CommonLog.MsgErrorInfo("绑定账号失败！" + msg);
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo(string.Format("绑定账号失败！手机号：{0}已绑定其它公众号", tel));
                                    }

                                }
                                else
                                {
                                    return CommonLog.MsgErrorInfo("账号错误！");
                                }
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo(string.Format("绑定账号失败！已绑定手机号:{0}", wxCustomer.Mobile));

                            }
                        }
                        catch (Exception ee)
                        {

                            Logger.Info(this.GetType(), "BindOnAccount ee:" + ee.StackTrace);
                            //TODO  日志
                            return CommonLog.MsgErrorInfo("绑定账号失败！");
                        }
                        //合并为只有一个用户，如果有微信的资料则合并到微信的资料中 ,调用存储过程，因为涉及的表太多

                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("微信账号不正确");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("绑定参数不正确");
                }
            }
            catch (Exception ex)
            {
                Logger.Info(this.GetType(), "BindOnAccount ex:" + ex.StackTrace);
                //TODO 日志 
                return CommonLog.MsgErrorInfo(ex.Message);

                throw;
            }

        }
        private string ExceProcedure(int _newcustomerId, string _tel, string _pwd)
        {
            string msg = "";
            //////////////////////////////////////////////////////////////////////////////
            ///获取用户名、邮件及设定密码，增加到数据库的用户表后返回该用户注册id值，不考虑 安全，仅仅表示代码的写作范例是否合乎要求
            ///存储过程为：
            ///CREATE PROCEDURE `yuan_user_cc`(in xname varchar(100),in xemail varchar(100),in xpassword varchar(100),out xid integer)
            ///begin
            ///insert into yuan_user(name,email,password) values(xname,xemail,xpassword);
            ///select id into xid from yuan_user where name=xname;
            ///end
            //////////////////////////////////////////////////////////////////////////////
            var procedureName = "proc_bindonaccount";
            MySqlDataAdapter mysqldata = new MySqlDataAdapter();

            DataSet dataset = new DataSet();
            mysqldata.SelectCommand = new MySqlCommand();
            mysqldata.SelectCommand.Connection = new MySqlConnection(GetDBString());
            mysqldata.SelectCommand.CommandText = procedureName;
            mysqldata.SelectCommand.CommandType = CommandType.StoredProcedure;
            //设置参数，添加到数据库
            MySqlParameter newcustomerId = new MySqlParameter("?newcustomerId", MySqlDbType.VarChar, 100);//mysql的存储过程参数是以?打头的！！！！
            newcustomerId.Value = _newcustomerId;
            mysqldata.SelectCommand.Parameters.Add(newcustomerId);
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            MySqlParameter tel = new MySqlParameter("?_tel", MySqlDbType.VarChar, 100);//mysql的存储过程参数是以?打头的！！！！
            tel.Value = _tel;
            mysqldata.SelectCommand.Parameters.Add(tel);

            MySqlParameter pwd = new MySqlParameter("?_pwd", MySqlDbType.VarChar, 100);//mysql的存储过程参数是以?打头的！！！！
            pwd.Value = _pwd;
            mysqldata.SelectCommand.Parameters.Add(pwd);

            //++++++++++++++++++++++++++ 如果存储过程有返回值++++++++++++++++++++++++++++++++++++++++++
            //MySqlParameter id_parameter = new MySqlParameter("?id", MySqlDbType.Int16, 15);//mysql的存储过程参数是以?打头的！！！！
            //id_parameter.Direction = ParameterDirection.Output;
            //mysqldata.SelectCommand.Parameters.Add(id_parameter);

            //+++++++++++++++++++++++++打开数据库，插入数据，返回id值+++++++++++++++++++
            try
            {
                mysqldata.Fill(dataset, procedureName);
            }
            catch (MySqlException ex)
            {
                Logger.Info(this.GetType(), "ExceProcedure ex:" + ex.StackTrace);
                msg = ex.Message;
            }
            return msg;
        }
        private string GetDBString()
        {
            string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/IBatis/sqlMap.config");
            if (File.Exists(xmlPath))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                XmlNamespaceManager xmlnam = new XmlNamespaceManager(xmlDoc.NameTable);
                xmlnam.AddNamespace("a", "http://ibatis.apache.org/dataMapper");
                var a_node = xmlDoc.SelectSingleNode(@"/a:sqlMapConfig/a:database/a:dataSource", xmlnam);
                if (a_node != null && a_node.OuterXml.Contains("connectionString"))
                {
                    return a_node.Attributes["connectionString"].Value;
                }
                return "";
            }
            else
            {

                Logger.Info(this.GetType(), "GetDBString,文件路径不存在：" + xmlPath);
                return "";

            }
        }
        public static string readXMLFile(string key)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath("~") + @"Language\" + key + "CommonXML.xml"))
            {
                string xmlFile = "";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(HttpContext.Current.Server.MapPath("~") + @"Language\" + key + "CommonXML.xml");
                XmlNode root = xmlDoc.SelectSingleNode("ROOT/" + key);
                XmlNodeList list = root.ChildNodes;
                foreach (XmlNode r in list)
                {
                    if (r.ChildNodes.Count > 0)
                    {
                        XmlNodeList rlist = r.ChildNodes;
                        foreach (XmlNode z in rlist)
                        {
                            if (!string.IsNullOrEmpty(z.InnerText))
                            {
                                z.InnerText = ("," + z.InnerText).Replace(",", "," + r.Name + ".");
                                xmlFile += z.InnerText;
                            }
                        }
                    }
                }
                System.Web.HttpContext.Current.Cache.Insert("Cache:xmlFile" + key, xmlFile, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
                return xmlFile;
            }
            return "";
        }
        private static void SendMsg(string tel, string salesName, string customerName, string snStr)
        {
            //sms
            HashParam hsParam2 = new HashParam();
            hsParam2["salesname"] = salesName;
            hsParam2["customer"] = customerName;
            hsParam2["time"] = DateTime.Now.ToString("MM月dd日HH点mm分");
            hsParam2["sn"] = snStr + "...";
            SMSManager.SendSms(tel, SMSLib.SMSTemplateByHasReg, hsParam2); //客户
            //sms end
        }
        #region 流水
        /// <summary>
        /// 添加流水
        /// </summary>
        /// <param name="addExpenseParam"></param>
        /// <returns></returns>
        public string AddFlow(string addFlowParam)
        {
            logParam = addFlowParam;
            string tttagKey = CommonUrl.getURL(null, addFlowParam);
            //templateJSON
            FlowInfo param = Json.Deserialize<FlowInfo>(addFlowParam);
            try
            {
                //可行性判断
                #region
                //提现，提现金额不能大于当前余额
                if (param.Abstract == 5 && (param.Balance < param.Amount))
                {
                    return CommonLog.MsgErrorInfo("提现失败,提现金额不能大于当前余额");
                }
                #endregion
                param.CreateTime = DateTime.Now;//申请时间
                using (ITransaction trans_addFlow = YZ.GetTransaction(tttagKey))
                {
                    int addFlowResult = trans_addFlow.Add(param);
                    if (addFlowResult > 0)
                    {
                        try
                        {
                            trans_addFlow.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("申请成功");
                        }
                        catch (Exception e)
                        {
                            trans_addFlow.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("申请失败,请重试");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("申请失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 修改流水 
        /// </summary>
        /// <param name="editFlowParam"></param>
        /// <returns></returns>
        public string EditFlow(string editFlowParam)
        {
            logParam = editFlowParam;
            string tttagKey = CommonUrl.getURL(null, editFlowParam);
            //ID（必传）
            //templateJSON
            FlowInfo param = Json.Deserialize<FlowInfo>(editFlowParam);
            try
            {
                FlowInfo _flow = YZ.GetDatabase(tttagKey).QueryForObject<FlowInfo>("Flow.GetFlowByID", param);//flow.ID
                if (_flow.Status == 0)
                {
                    param.CreateTime = DateTime.Now;//申请时间
                    using (ITransaction trans_editFlow = YZ.GetTransaction(tttagKey))
                    {
                        int editFlowResult = trans_editFlow.Edit(param);
                        if (editFlowResult > 0)
                        {
                            try
                            {
                                trans_editFlow.CommitTransaction();//提交事务
                                return CommonLog.MsgSuccessInfo("修改成功");
                            }
                            catch (Exception)
                            {
                                trans_editFlow.RollBackTransaction();//回滚事务
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                        }
                        return CommonLog.MsgErrorInfo("修改失败");
                    }
                }
                else
                {
                    //已审核 1 已作废-1
                    return CommonLog.MsgErrorInfo("修改失败,请选择待审核记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改失败，程序错误");
            }
        }
        /// <summary> 
        /// 导出银行收支 12-10
        /// </summary>
        /// <param name="expFlowsParam"></param>
        /// <returns></returns>
        public string ExportFlows(string expFlowsParam)
        {
            logParam = expFlowsParam;
            HashParam param = Json.Deserialize<HashParam>(expFlowsParam);
            string tttagKey = CommonUrl.getURL(param, expFlowsParam);
            string FileName = "收支 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<FlowResult> FlowList = YZ.GetDatabase(tttagKey).QueryForList<FlowResult>("Flow.GetFlows", param);//收支IList
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>账户</td>");
                OutFileContent.Append("<td>支出</td>");
                OutFileContent.Append("<td>收入</td>");
                OutFileContent.Append("<td>结余</td>");
                OutFileContent.Append("<td>到账时间</td>");
                OutFileContent.Append("<td>交易类型</td>");
                OutFileContent.Append("<td>状态</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (FlowList != null && FlowList.Count > 0)
                {
                    for (int i = 0; i < FlowList.Count; i++)
                    {
                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + AccountFormat(FlowList[i].Account) + "</td>");
                        if (FlowList[i].Type == 1)
                        {
                            //Type=1 收入
                            columnValue.Append("<td>-</td>");
                            columnValue.Append("<td>" + FlowList[i].Amount + "</td>");
                        }
                        else
                        {
                            //Type=2 支出
                            columnValue.Append("<td>" + FlowList[i].Amount + "</td>");
                            columnValue.Append("<td>-</td>");
                        }
                        columnValue.Append("<td>" + FlowList[i].Balance + "</td>");
                        columnValue.Append("<td>" + FlowList[i].ArrivalTime + "</td>");
                        columnValue.Append("<td>" + TypeFormat(FlowList[i].Type) + "</td>");
                        columnValue.Append("<td>" + StatusFormat(FlowList[i].Status) + "</td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + ChargeList.Count + "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    //返回文件下载地址 http://localhost:3952/excel/xx.xls
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出失败:");
            }
        }
        /// <summary>
        /// 流水记录统计 12-13
        /// </summary>
        /// <param name="flowNumberParam"></param>
        /// <returns></returns>
        public string FlowNumber(string flowNumberParam)
        {
            logParam = flowNumberParam;
            HashParam param = Json.Deserialize<HashParam>(flowNumberParam);
            string tttagKey = CommonUrl.getURL(param, flowNumberParam);
            //templateJSON
            try
            {
                IList<FlowResult> _flowInfo = YZ.GetDatabase(tttagKey).QueryForList<FlowResult>("Flow.GetFlowNumber", param);
                if (_flowInfo != null && _flowInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_flowInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 审核流水 Status 必须=0待审核 -多事务
        /// </summary>
        /// <param name="modifyFlowParam"></param>
        /// <returns></returns>
        public string ModifyFlow1(string modifyFlowParam)
        {
            logParam = modifyFlowParam;
            string tttagKey = CommonUrl.getURL(null, modifyFlowParam);
            //templateJSON
            FlowInfo flow = Json.Deserialize<FlowInfo>(modifyFlowParam);
            try
            {
                //FlowInfo _flow = YZ.GetDatabase(tttagKey).Get<FlowInfo>(flow);
                FlowInfo _flow = YZ.GetDatabase(tttagKey).QueryForObject<FlowInfo>("Flow.GetFlowByID", flow);//flow.ID
                //待审核0
                if (_flow.Status == 0)
                {
                    //2.检查能否审核
                    flow.UpdateTime = DateTime.Now;//审核时间
                    //通过审核1
                    if (flow.Status == 1)
                    {
                        BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", flow);//flow.Account
                        //收入1 （出货款-国内账户+；退回供应商-HK-$+）
                        if (flow.Type == 1)
                        {
                            flow.Balance = _bank.BankBalance + flow.Amount;//本次结余 = 账户当前结余 + 本次交易金额Amount
                        }
                        else
                        {
                            //支出2 （到货款-HK-$-；客户退货-国内账户-）
                            flow.Balance = _bank.BankBalance + (-flow.Amount);//本次结余 = 账户当前结余 + (- 本次交易金额Amount)
                        }
                    }
                    using (ITransaction trans_modFlow = YZ.GetTransaction(tttagKey))
                    {
                        int modFlowResult = trans_modFlow.Edit(flow);
                        if (modFlowResult > 0)
                        {
                            //1已审核通过 
                            if (flow.Status == 1)
                            {
                                try
                                {
                                    //3.更新账户余额BankBalance
                                    #region
                                    BankInfo bankInfo = new BankInfo();
                                    bankInfo.BankID = flow.Account;//本次账户
                                    bankInfo.BankBalance = flow.Balance;//本次账户结余
                                    using (ITransaction trans_editBankBalance = YZ.GetTransaction(tttagKey))
                                    {
                                        //int editAccountBalanceResult = trans_editBankBalance.Update("Bank.EditBankBalance", bankInfo);//更新账户结余 -实际生效了.结果：Update无法使用事务 12-7
                                        int editAccountBalanceResult = trans_editBankBalance.Edit(bankInfo);//更新账户结余 -只能用Edit
                                        if (editAccountBalanceResult > 0)
                                        {
                                            try
                                            {
                                                //4.更新订单支付状态
                                                #region
                                                IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", flow.OrderIDs);//OrderIDs
                                                if (OrderList != null && OrderList.Count > 0)
                                                {
                                                    for (int i = 0; i < OrderList.Count; i++)
                                                    {
                                                        //未支付0
                                                        if (OrderList[i].PaymentStatus == 0)
                                                        {
                                                            OrderList[i].PaymentStatus = 1;//1已支付
                                                            OrderList[i].PayTime = DateTime.Now;//支付时间
                                                            using (ITransaction trans_editOrderPaymentStatus = YZ.GetTransaction(tttagKey))
                                                            {
                                                                int editOrderPaymentStatusResult = trans_editOrderPaymentStatus.Edit(OrderList[i]);//更新订单支付状态
                                                                if (editOrderPaymentStatusResult > 0)
                                                                {
                                                                    try
                                                                    {
                                                                        trans_editOrderPaymentStatus.CommitTransaction(); //触发入库事务
                                                                    }
                                                                    catch (Exception)
                                                                    {
                                                                        trans_editOrderPaymentStatus.RollBackTransaction();//回滚事务
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            //已支付1
                                                            return CommonLog.MsgErrorInfo("失败,存在已支付的订单");
                                                        }
                                                    }
                                                }
                                                #endregion
                                                trans_editBankBalance.CommitTransaction(); //触发入库事务
                                            }
                                            catch (Exception)
                                            {
                                                trans_editBankBalance.RollBackTransaction();//回滚事务
                                            }
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("更新账户结余失败");
                                        }
                                    }
                                    #endregion
                                    trans_modFlow.CommitTransaction(); //5.正式更新流水事务
                                    return CommonLog.MsgSuccessInfo("成功审核");
                                }
                                catch (Exception)
                                {
                                    //回滚事务
                                    trans_modFlow.RollBackTransaction();
                                }
                            }
                            else
                            {
                                // -1 已审核作废
                                try
                                {   //提交事务
                                    trans_modFlow.CommitTransaction(); //5.正式更新流水事务
                                    return CommonLog.MsgSuccessInfo("成功作废");
                                }
                                catch (Exception)
                                {
                                    //回滚事务
                                    trans_modFlow.RollBackTransaction();
                                }
                            }
                        }
                        else
                        {
                            trans_modFlow.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("失败,请检查流水标识");
                        }
                    }
                    return CommonLog.MsgErrorInfo("处理失败");
                }
                else
                {
                    //已审核1 已作废-1
                    return CommonLog.MsgErrorInfo("失败,流水已审核或已作废");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("处理失败");
            }
        }
        /// <summary>
        /// 单条流水
        /// </summary>
        /// <param name="chargeInfoParam"></param>
        /// <returns></returns>
        public string GetFlow(string getFlowParam)
        {
            logParam = getFlowParam;
            string tttagKey = CommonUrl.getURL(null, getFlowParam);
            //templateJSON
            FlowInfo param = Json.Deserialize<FlowInfo>(getFlowParam);
            try
            {
                FlowInfo FlowInfo = YZ.GetDatabase(tttagKey).Get<FlowInfo>(param);
                if (FlowInfo != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(FlowInfo));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取失败，请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 审核流水（1.更新流水为已审核1，2.更新银行账户结余，3.更新订单付款状态为已支付， 4.如果Type为3定金或4提现，还需更新客户余额） - 单事务 12-8 （重中之重）
        /// </summary>
        /// <param name="modifyFlowParam"></param>
        /// <returns></returns>
        public string ModifyFlow(string modifyFlowParam)
        {
            var logParam = modifyFlowParam;
            string tttagKey = CommonUrl.getURL(null, modifyFlowParam, "审核流水");
            //templateJSON
            FlowInfo flow = Json.Deserialize<FlowInfo>(modifyFlowParam);
            try
            {
                //FlowInfo _flow = YZ.GetDatabase(tttagKey).Get<FlowInfo>(flow);
                FlowInfo _DBflow = YZ.GetDatabase(tttagKey).QueryForObject<FlowInfo>("Flow.GetFlowByID", flow.ID);//flow.ID
                //待审核0
                if (_DBflow.Status == 0)
                {
                    //2.检查能否审核
                    flow.UpdateTime = DateTime.Now;//审核时间
                    //通过审核1
                    if (flow.Status == 1)
                    {
                        BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", flow.Account);//flow.Account
                        if (_bank != null)
                        {
                            //1启用
                            if (_bank.Status == 1)
                            {
                                //账户与币种不匹配
                                if (_bank.Currency != flow.Currency)
                                {
                                    return CommonLog.MsgErrorInfo("失败,账户与币种不匹配");
                                }
                                //0 不符 1相符 空 未对账
                                if (_bank.CheckResult == 1)
                                {
                                    //收入1 （出货款-国内账户+；退回供应商-HK-$+）  
                                    if (flow.Type == 1)
                                    {
                                        flow.Balance = _bank.BankBalance + flow.Amount;//本次结余 = 账户当前结余 + 本次交易金额Amount
                                    }
                                    //支出2 （到货款-HK-$-；客户退货-国内账户-）  
                                    else if (flow.Type == 2)
                                    {
                                        flow.Balance = _bank.BankBalance + (-flow.Amount);//本次结余 = 账户当前结余 - 本次交易金额Amount
                                    }
                                }
                                else
                                {
                                    //对账不符
                                    return CommonLog.MsgErrorInfo("失败,账户结余对账不相符,请对账相符后再审核");
                                }
                            }
                            else
                            {
                                //0禁用
                                return CommonLog.MsgErrorInfo("失败,账户已禁用,请启用账号后再审核");
                            }
                        }
                        else
                        {
                            //账户不存在
                            return CommonLog.MsgErrorInfo("失败,账户不存在,请检查标识");
                        }
                    }
                    using (ITransaction trans_modFlow = YZ.GetTransaction(tttagKey))
                    {
                        int modFlowResult = trans_modFlow.Edit(flow);
                        if (modFlowResult > 0)
                        {
                            //1已审核通过 
                            if (flow.Status == 1)
                            {
                                //3.更新账户余额BankBalance
                                #region
                                BankInfo bankInfo = new BankInfo();
                                bankInfo.BankID = flow.Account;//本次账户
                                bankInfo.BankBalance = flow.Balance;//本次账户结余
                                bankInfo.UpdateTime = DateTime.Now;
                                //int editAccountBalanceResult = trans_editBankBalance.Update("Bank.EditBankBalance", bankInfo);//更新账户结余 -实际生效了.结果：Update无法使用事务 12-7
                                int editAccountBalanceResult = trans_modFlow.Edit(bankInfo);//更新账户结余 -只能用Edit
                                if (editAccountBalanceResult > 0)
                                {
                                    //操作类型（摘要）Abstract = 1到8
                                    #region
                                    if (flow.Abstract == 1)
                                    {
                                        //Abstract 1支付+  (更新订单支付状态未支付的为已支付)
                                        #region
                                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", flow.OrderIDs);//OrderIDs
                                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                                        if (OrderList != null && OrderList.Count > 0)
                                        {
                                            for (int i = 0; i < OrderList.Count; i++)
                                            {
                                                //未支付0
                                                if (OrderList[i].PaymentStatus == 0)
                                                {
                                                    OrderList[i].PaymentStatus = 1;//1已支付
                                                    OrderList[i].PayTime = DateTime.Now;//支付时间
                                                    int editOrderPaymentStatusResult = trans_modFlow.Edit(OrderList[i]);//更新订单支付状态
                                                    if (editOrderPaymentStatusResult > 0)
                                                    {
                                                        //忽略
                                                    }
                                                    else
                                                    {
                                                        return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                                    }
                                                }
                                                else
                                                {
                                                    //已支付1
                                                    return CommonLog.MsgErrorInfo("失败,存在已支付的订单");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //无订单 -提交事务
                                            //忽略
                                        }
                                        #endregion
                                    }
                                    else if (flow.Abstract == 2)
                                    {
                                        //Abstract 2充值+ (更新客户余额) 
                                        #region
                                        CustomerInfo _customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(flow.CustomerID);
                                        if (_customer != null)
                                        {
                                            //Currency=1 人民币 2017-01-18
                                            if (flow.Currency == 1)
                                            {
                                                _customer.Balance += flow.Amount;//客户人民币余额 = 客户当前余额 + 收入金额(定金) 
                                            }
                                            else if (flow.Currency == 2)
                                            {
                                                //美金
                                                _customer.USDBalance += flow.Amount;//客户美金余额
                                            }
                                            int editBalanceResult = trans_modFlow.Edit(_customer);//更新客户余额 Customer.Balance为无符号字段 所以-3000将报错
                                            if (editBalanceResult > 0)
                                            {
                                                //更新流水客户余额 12-29
                                                if (flow.Currency == 1)
                                                {
                                                    flow.CustomerBalance = _customer.Balance;//人民币结余
                                                }
                                                else if (flow.Currency == 2)
                                                {
                                                    flow.CustomerBalance = _customer.USDBalance;//美金结余
                                                }
                                                flow.Comments += ";充值" + flow.Amount + "到客户余额";
                                                int editFlowResult = trans_modFlow.Edit(flow);//更新收入记录
                                                if (editFlowResult > 0)
                                                {
                                                    //继续
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("失败,更新流水客户余额失败");
                                                }
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("更新客户余额失败");
                                            }
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("失败，客户不存在，请检查客户标识");
                                        }
                                        #endregion
                                    }
                                    else if (flow.Abstract == 3)
                                    {
                                        //Abstract 3退回
                                        //忽略
                                        //成功退回后如果已支付，已自动充值到客户余额
                                    }
                                    else if (flow.Abstract == 4)
                                    {
                                        //Abstract 4自留
                                        //成功自留后如果已支付，已自动充值到客户余额
                                        //忽略
                                    }
                                    else if (flow.Abstract == 5)
                                    {
                                        //20180410 修改。 
                                        trans_modFlow.Edit(flow);//更新记录
                                    }
                                    else if (flow.Abstract == 6)
                                    {
                                        //Abstract 6确认到货-
                                        #region
                                        //账户结余大于0
                                        if (flow.Balance >= 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("失败,账户结余不足");
                                        }
                                        #endregion
                                    }
                                    else if (flow.Abstract == 7)
                                    {
                                        //Abstract 7取消到货+
                                    }
                                    else if (flow.Abstract == 8)
                                    {
                                        //Abstract 8申请收支
                                        #region
                                        //账户支出时结余大于0才可行
                                        if (flow.Type == 2)
                                        {
                                            if (flow.Balance < 0)
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("失败,账户结余不足,请先入账");
                                            }
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                    }
                                    #endregion
                                    // 1 已通过审核
                                    try
                                    {   //提交事务                                        
                                        trans_modFlow.CommitTransaction(); //5.正式更新流水事务
                                        CommonLog.SendMQMsg(tttagKey, "审核通过成功：" + modifyFlowParam);
                                        return CommonLog.MsgSuccessInfo("审核通过成功");
                                    }
                                    catch (Exception ex)
                                    {
                                        //回滚事务
                                        trans_modFlow.RollBackTransaction();
                                        CommonLog.SendMQMsg(tttagKey, "异常信息：审核通过失败" + ex.StackTrace + "参数:" + logParam);
                                        return CommonLog.MsgErrorInfo("审核通过失败");
                                    }
                                }
                                else
                                {
                                    return CommonLog.MsgErrorInfo("更新账户结余失败");
                                }
                                #endregion
                            }
                            else
                            {
                                //提现 不通过
                                if (flow.Abstract == 5)
                                {
                                    //不通过，客户余额增加
                                    //20180410 修改。
                                    CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(flow.CustomerID);//CustomerID必传
                                    if (customer != null)
                                    {
                                        if (flow.Currency == 1)
                                        {
                                            customer.Balance += flow.Amount;
                                        }
                                        else if (flow.Currency == 2)
                                        {
                                            customer.USDBalance += flow.Amount;
                                        }
                                    }
                                    trans_modFlow.Edit(customer);//更新记录
                                }
                                // -1 已审核作废
                                try
                                {   //提交事务
                                    trans_modFlow.CommitTransaction(); //5.正式更新流水事务
                                    CommonLog.SendMQMsg(tttagKey, "作废成功：" + modifyFlowParam);
                                    return CommonLog.MsgSuccessInfo("作废成功");
                                }
                                catch (Exception)
                                {
                                    //回滚事务
                                    trans_modFlow.RollBackTransaction();
                                    return CommonLog.MsgErrorInfo("作废失败");
                                }
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,请检查流水标识");
                        }
                    }
                }
                else
                {
                    //已审核1 已作废-1
                    return CommonLog.MsgErrorInfo("失败,流水已审核或已作废");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：审核流水" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("处理失败");
            }
        }
        #endregion
        #endregion
        #region Notice通知相关
        /// <summary>
        /// 单个公告
        /// </summary>
        /// <param name="customerInfoParam"></param>
        /// <returns></returns>
        public string GetNoticeInfo(string strParam)
        {
            return CRetails.GetNoticeInfo(strParam);
        }
        /// <summary>
        /// 浏览公告
        /// </summary>
        /// <param name="noticeInfoParam"></param>
        /// <returns></returns>
        public string ViewNoticeInfo(string strParam)
        {
            return CRetails.ViewNoticeInfo(strParam);
        }
        /// <summary>
        /// 发布公告
        /// </summary>
        /// <param name="addCustomerParam"></param>
        /// <returns></returns>
        public string AddNotice(string strParam)
        {
            return CRetails.AddNotice(strParam);
        }
        /// <summary>
        /// 修改公告
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public string EditNotice(string strParam)
        {
            return CRetails.EditNotice(strParam);
        }
        /// <summary>
        ///  紧急通知
        /// </summary>
        /// <returns></returns>
        public string GetNotice(string strParam)
        {
            return CRetails.GetNotice(strParam);
        }
        /// <summary>
        /// 所有公告
        /// </summary>
        /// <param name="getCustomersParam"></param>
        /// <returns></returns>
        public string GetNotices(string strParam)
        {
            return CRetails.GetNotices(strParam);
        }
        /// <summary>
        /// 所有发布中公告 11-16
        /// </summary>
        /// <param name="getNoticesParam"></param>
        /// <returns></returns>
        public string GetNoticeList(string strParam)
        {
            return CRetails.GetNoticeList(strParam);
        }
        #endregion
        #region 裸钻库存相关
        /// <summary>
        /// 获取单个在线库存
        /// </summary>
        /// <param name="inventoryInfoParam"></param>
        /// <returns></returns>
        public string GetInventoryInfo(string inventoryInfoParam)
        {
            logParam = inventoryInfoParam;
            string tttagKey = CommonUrl.getURL(null, inventoryInfoParam);
            //SearchProductLogs(logParam);
            InventoryInfo param = Json.Deserialize<InventoryInfo>(inventoryInfoParam); //反序列化为PageParamOfInventory类型   //Deserialize 反序列化
            InventoryInfoResult inventoryResult = new InventoryInfoResult();
            try
            {
                if (param.CertNo == null || param.CertNo == "")
                {
                    //库存号Inventory
                    inventoryResult = (InventoryInfoResult)GetInventoryInfoByCerNoStr(param.ID.ToString(), tttagKey, true);
                }
                else
                {
                    //证书号CertNo
                    inventoryResult = (InventoryInfoResult)GetInventoryInfoByCerNoStr(param.CertNo, tttagKey);
                }

                dynamic setting = GoodsType.GetSystemSetting<SysSettingInfo>(tttagKey, GoodsType.Diamond); // new SystemSetting(GoodsType.Diamond);//裸钻

                //CustomerInfo customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(Convert.ToInt32(param.CustomerId));//CustomerID值如存在，就按客户的价格；不存在就是团队的价格 
                DiamondsPriceHandler.ComputePrice(tttagKey, inventoryResult, setting);//计算价格 

            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("获取库存失败，请检查服务");
            }
            return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(inventoryResult));
        }
        /// <summary>
        /// 获取单个在线库存，通过证书号CertNo
        /// </summary>
        /// <param name="certNo"></param>
        /// <param name="isUseInventoryid"></param>
        /// <returns></returns>
        public InventoryInfo GetInventoryInfoByCerNoStr(string certNo, string key, bool isUseInventoryid = false)
        {
            logParam = ",certNo:" + certNo + ",isUseInventoryid:" + isUseInventoryid.ToString();

            var requestJson = string.Empty;
            if (isUseInventoryid)
                requestJson = string.Format("{{  \"useDict\": true, \"ID\": \"{0}\"}}", certNo);
            else
                requestJson = string.Format("{{  \"useDict\": true, \"CertNo\": \"{0}\"}}", certNo);
            int totalSeconds;
            string signStr;
            var guid = Guid.NewGuid().ToString();
            var objParams = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestJson);
            var lastStr = MyHttpRequest.ShotDic1(objParams);
            MyHttpRequest.SignByParams(guid, lastStr.ToString(), key, out totalSeconds, out signStr);
            PageList<InventoryInfoResult> model_InventoryInfoList = new PageList<InventoryInfoResult>();
            try
            {
                model_InventoryInfoList = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(  //序列化成 InventoryInfo
                  MyHttpRequest.ConvertToInventoryFormat(                //格式化库存的格式
                       MyHttpRequest.PostJSONByRequestParam(             //传递请求参数
                          new RequestInfo() { RequestJson = requestJson, RequestUrl = GlobalConfig.IUrl }  //获取请求参数
                          , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST
                       )
                   )
                );
            }
            catch (Exception ee)
            {
                Logger.Info(this.GetType(), "msg:" + ee.Message);
            }
            InventoryInfo info = new InventoryInfo();
            if (model_InventoryInfoList != null && model_InventoryInfoList.Data != null && model_InventoryInfoList.Data.Count > 0)
            {
                info = (InventoryInfo)model_InventoryInfoList.Data[0];
            }
            return info;
        }
        public string GetInventoryInfosCount(string inventoryInfoParam)
        {
            logParam = inventoryInfoParam;
            string tttagKey = CommonUrl.getURL(null, inventoryInfoParam);
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"ShowCount\":#showcount,\"TotalCount\":#result}";
            PageParamOfInventory param = JsonConvert.DeserializeObject<PageParamOfInventory>(inventoryInfoParam); //反序列化为PageParamOfInventory类型   //Deserialize 反序列化
            if (param.IsStock == 1) //现货加入对应供应商设置
            {
                if (param.Supplier == null)
                {
                    param.Supplier = new string[1];
                }
                new string[] { tttagKey }.CopyTo(param.Supplier, 0);
            }
            //获取在线库存统计（含签名）
            param.PageCount = 0;  //这个很重要，拿返回总数一定要设置为0
            param.onlyCount = true;
            var requestJson = CWholesalers.ConvertAndFormatToJSON(param);  //格式化 转换成仓库所需要的JSON
            var guid = Guid.NewGuid().ToString();
            var objParams = JsonConvert.DeserializeObject<JObject>(requestJson);
            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams).Replace("Weight", "Weight1");
            int totalSeconds;
            string signStr;
            MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
            var rif = new RequestInfo() { RequestJson = requestJson, RequestUrl = GlobalConfig.TransmissionUpStockURL + "filters/" };
            var countJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST);
            var countDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(countJson);
            if (countDic["result"].ToLower() == "true")
            {
                return _msgInfo.Replace("#code", "true").Replace("#msg", "成功").Replace("#showcount", CommonLog.showCount).Replace("#result", countDic["count"]);
            }
            else
                return _msgInfo.Replace("#code", "false").Replace("#msg", "失败").Replace("#showcount", CommonLog.showCount).Replace("#result", "0");
        }
        #region   去上一级查货
        public string GetProductsByYiJi(string inventoryInfoParam, string token = "")
        {
            YIJIServiceReference.SubServiceClient subServiceClient = new YIJIServiceReference.SubServiceClient();
            return subServiceClient.QueryStock(inventoryInfoParam, token);
        }
   
        /// <summary>
        /// 裸钻 二级零售去一级零售查货
        /// </summary>
        /// <param name="inventoryInfoParam"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public string QueryStockFromUpper(string strParam)
        {
            SubRetailReference.SubRetailClient subRetailClient = new SubRetailReference.SubRetailClient();
            return subRetailClient.QueryStock(strParam);
        }
        /// <summary>
        /// 其他商品 二级零售去一级零售查货
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string QueryProductDataFromUpper(string strParam)
        {
            SubRetailReference.SubRetailClient subRetailClient = new SubRetailReference.SubRetailClient();
            return subRetailClient.QueryProductData(strParam); 
        }
        #endregion
        /// <summary>
        /// 获取多个在线库存数据 （公司客户和团队）  PageList<InventoryInfoResult>
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string GetInventoryInfos(string inventoryInfoParam, string key = "")
        {
            logParam = inventoryInfoParam;
            inventoryInfoParam = inventoryInfoParam.Replace("Weight", "weight");
            //WeightMax: "5.50"WeightMin: "0.30"   limit   regexp{CertNo,SN,OriginSN}
            string tttagKey = "";
            var secondSn = string.Empty;
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"data\":#result}";
            try
            {
                HashParam hashParam = JsonConvert.DeserializeObject<HashParam>(inventoryInfoParam);
                hashParam.Remove("weight");
                hashParam.Remove("limit");
                if (hashParam.ContainsKey("weightMax") && hashParam.ContainsKey("weightMin"))
                {
                    if (hashParam.GetString("weightMax") == "5.50" && hashParam.GetString("weightMin") == "0.30")
                    {
                        //范围全部的话删除不传
                        hashParam.Remove("weightMax");
                        hashParam.Remove("weightMin");
                    }
                }

                var open_Interface = string.Empty;
                if (key == "open_Interface")  //开放平台接口使用
                {
                    open_Interface = key;
                    key = "";
                    secondSn = hashParam.GetString("SecondSN");//二级的供应商
                    hashParam.Remove("SecondSN");
                }
                if (!string.IsNullOrEmpty(key))
                {
                    tttagKey = key;
                }
                else
                {
                    if((hashParam.ContainsKey("ErJiMark") && string.IsNullOrEmpty(secondSn))|| (!hashParam.ContainsKey("ErJiMark") && string.IsNullOrEmpty(secondSn)))
                        tttagKey = CommonUrl.getURL(hashParam, inventoryInfoParam, "查询库存");
                    else
                        tttagKey = CommonUrl.getURL(hashParam, inventoryInfoParam);
                } 
                #region isBig 重量大小排序逻辑
                if (hashParam.ContainsKey("isBig") && hashParam.GetBool("isBig"))
                {
                    if (!hashParam.ContainsKey("SortColumn"))
                    {
                        hashParam.Add("SortColumn", "OriginUSDPerGrain");
                        hashParam.Add("SortDirect", "asc");
                    }
                    //inventoryInfoParam = JsonConvert.SerializeObject(hashParam);
                }
                #endregion
                //Json.Deserialize 该反序列化方式用在这是个大坑 2016-8-13
                // PageParamOfInventory param = JsonConvert.DeserializeObject<PageParamOfInventory>(inventoryInfoParam);
                CustomerInfo customerInfo = null;
                #region 客户查询限制 和供应商权限过滤
                //if (param.CustomerID > 0) //如果是客户查询，
                if (hashParam.ContainsKey("CustomerID") && hashParam.GetInt("CustomerID") > 0) //如果是客户查询，
                {
                    //customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.CustomerID);//CustomerID值如存在，就按客户的价格；不存在就是团队的价格 
                    customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(hashParam.GetInt("CustomerID"));//CustomerID值如存在，就按客户的价格；不存在就是团队的价格 
                                                                                                              //验证查询次数
                                                                                                              //customerInfo
                                                                                                              ////加上对应角色的供应商信息

                    if (customerInfo == null || customerInfo.SysStatus != 1)
                    {
                        return _msgInfo.Replace("#code", "false").Replace("#msg", "无效的用户不能查询库存，请联系管理员").Replace("#result", JsonConvert.SerializeObject(""));
                    }
                    //if (customerInfo != null && customerInfo.SearchCountFlag == 0 && param.UserID == 0)//param.UserID 表示只有客户自己查询
                    if (customerInfo.SearchCountFlag == 0 && hashParam.ContainsKey("UserID") && hashParam.GetInt("UserID") == 0)//param.UserID 表示只有客户自己查询
                    {
                        return _msgInfo.Replace("#code", "false").Replace("#msg", "你今天查询过多,暂无权限.").Replace("#result", JsonConvert.SerializeObject(""));
                    }
                    if (customerInfo.RoleNames != null && customerInfo.RoleNames != "")  //如果有供应商的权限
                    {
                        Hashtable table = new Hashtable();
                        table.Add("RoleNames", customerInfo.RoleNames.TrimEnd(',').Split(','));
                        table.Add("GoodsType", GoodsType.Diamond);
                        var supplierNameList = YZ.GetDatabase(tttagKey).QueryForList<string>("Supplier.GetSupplierNameBySupplierNames", table);
                        if (supplierNameList.Count > 0)
                        {
                            //未添加任何供应商的参数，展示所有角色包含的供应商
                            //if (param.Supplier == null)
                            //{
                            //    param.Supplier = new string[supplierNameList.Count];
                            //    supplierNameList.ToArray().CopyTo(param.Supplier, 0);
                            //}
                            if (!hashParam.ContainsKey("Supplier"))
                            {
                                hashParam.Add("Supplier", supplierNameList.ToArray());
                            }
                            else
                            {
                                bool isInRole = false;
                                foreach (var supplierName in supplierNameList)
                                {
                                    //如果传的供应商在角色里面
                                    //if (param.Supplier[0] == supplierName)
                                    var supplierObj = ((JArray)hashParam["Supplier"]);
                                    foreach (var item in supplierObj)
                                    {
                                        if (item.ToString() == supplierName)
                                        {
                                            isInRole = !isInRole;
                                            break;
                                        }
                                    }
                                }
                                if (!isInRole)
                                {
                                    //不在角色里面的供应商请求直接返回没有库存
                                    return _msgInfo.Replace("#code", "false").Replace("#msg", "没有对应供应商的库存").Replace("#result", JsonConvert.SerializeObject(""));
                                }
                            }
                        }
                    }
                }
                #endregion
                if (hashParam.ContainsKey("IsStock") && hashParam.ContainsKey("IsExclude"))
                {
                    hashParam.Remove("IsStock");
                    hashParam.Remove("IsExclude");
                }
                #region   现货 ，订货 

                //if (param.IsStock == 1)
                bool stockFlag = false;
                if (hashParam.GetInt("IsStock", 0) == 1)
                {
                    //if (param.Supplier == null || param.Supplier.Count(p => p == tttagKey) > 0)
                    //{
                    //param.Supplier = new string[1];
                    //param.Supplier[0] = tttagKey;
                    hashParam["Supplier"] = new string[1] { tttagKey };
                    stockFlag = true;
                    hashParam.Remove("IsStock");
                    //}
                    //new string[] { tttagKey }.CopyTo(param.Supplier, 0);
                }
                if (hashParam.ContainsKey("IsExclude"))
                {
                    Dictionary<string, string[]> exclude = new Dictionary<string, string[]>();
                    exclude.Add("Supplier", tttagKey.Split(','));
                    hashParam["exclude"] = exclude;
                }
                #endregion
                string responseJson;
                PageList<InventoryInfoResult> result = new PageList<InventoryInfoResult>();
                ////传了现货，但是没有现货供应商
                //if (param.Supplier != null && param.Supplier.Count() == 0)
                if (hashParam.ContainsKey("Supplier") && hashParam["Supplier"].ToString() == "")
                {
                    responseJson = "{\"count\": 0, \"records\": 0, \"rows\": [], \"result\": true}";  //这responseJson 没有用上
                }
                else
                {
                    if (!hashParam.ContainsKey("useDict"))
                        hashParam.Add("useDict", "true");
                    if (!hashParam.ContainsKey("pageIndex"))
                        hashParam.Add("pageIndex", 1);
                    if (!hashParam.ContainsKey("pageSize"))
                        hashParam.Add("pageSize", CommonLog.showCount);//返回设定数据
                    if (!hashParam.ContainsKey("useDict"))
                        hashParam.Add("useDict", "true");
                    if (hashParam.ContainsKey("CertNo") || hashParam.ContainsKey("OriginSN") || hashParam.ContainsKey("SN"))
                    {
                        Dictionary<string, JArray> dss = new Dictionary<string, JArray>();
                        if (hashParam.ContainsKey("CertNo"))
                            dss.Add("CertNo", hashParam["CertNo"] as JArray);
                        if (hashParam.ContainsKey("SN"))
                        {
                            JArray snArray = new JArray();
                            snArray.Add(hashParam.GetString("SN"));
                            dss.Add("SN", snArray);
                        }
                        if (hashParam.ContainsKey("OriginSN"))
                            dss.Add("OriginSN", hashParam["OriginSN"] as JArray);
                        if(!hashParam.ContainsKey("regexp"))
                            hashParam.Add("regexp", dss);
                    }


                    if (hashParam.ContainsKey("ParentKey") && hashParam["ParentKey"].ToString() != "")
                    {
                        if (!hashParam.ContainsKey("ErJiMark"))
                        {
                            return _msgInfo.Replace("#code", "false").Replace("#msg", "获取库存失败，缺少必需的参数ErJiMark");
                        }

                        hashParam["TagKey"] = tttagKey.Split(new string[] { "__" },StringSplitOptions.None)[0]; //上一级需要加上一级自己的key
                        if(!hashParam.ContainsKey("SecondSN"))
                            hashParam["SecondSN"] = tttagKey; //上一级需要加上一级自己的key
                        var token = hashParam.GetString("ParentKey");
                        
                        hashParam.Remove("IsStock");
                        hashParam.Remove("CustomerID"); //移除二级本身的客户ID   
                        if (hashParam["ErJiMark"].ToString() == "2LSto1LS"&&!stockFlag)//数据来源 2级零售版本，它的数据来源是一级零售
                        {
                            hashParam.Remove("ErJiMark");
                            var requestParam = JsonConvert.SerializeObject(hashParam);
                            responseJson = QueryStockFromUpper(requestParam);
                        }
                        else if (hashParam["ErJiMark"].ToString() == "2LSto1PF")//这里是给其他的二级查货
                        {
                            //2LStoPF
                            hashParam.Remove("ParentKey");
                            var requestParam = JsonConvert.SerializeObject(hashParam);
                            responseJson = GetProductsByYiJi(requestParam, token);
                        }
                        else
                        {
                            responseJson = "";//暂时
                        }
                        //去一级用完一级的key后，得重新赋值成自己的key
                        if (hashParam.ContainsKey("SecondSN"))
                            tttagKey = hashParam["SecondSN"].ToString();
                        HashParam _param = JsonConvert.DeserializeObject<HashParam>(responseJson);
                        if (_param.ContainsKey("msgcode") && _param.GetBool("msgcode") && _param.ContainsKey("data") && _param.GetString("data").Length > 130) //有时data直接为[] (length为125左右) 但是查询正确，操蛋
                        {
                            responseJson = _param.GetString("data");
                            result = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(responseJson); //解析结果，转成PageList<InventoryInfoResult>格式

                        }
                        else
                        {
                            return responseJson;
                        }
                    }
                    else
                    {

                        hashParam.Remove("ParentKey");
                        var requestParam = JsonConvert.SerializeObject(hashParam);
                        hashParam.Remove("TagKey");
                        //获取在线库存（含签名）
                        //var requestJson = CWholesalers.ConvertAndFormatToJSON(param);  //格式化 转换成仓库所需要的JSON
                        var requestUrl = GlobalConfig.TransmissionUpStockURL + "filters/";  //V1版本请求地址
                        responseJson = MyHttpClient.GetRsultFromDataCenterNew(tttagKey, requestUrl, requestParam, 1, null);
                        responseJson = MyHttpRequest.ConvertToInventoryFormat(responseJson); //转化成库存的格式 (_Rapnet)
                        result = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(responseJson); //解析结果，转成PageList<InventoryInfoResult>格式
                    }
                }

                //result不为null
                if (result != null)
                {
                    //搜索条件无结果

                    //计算价格
                    #region 
                    //if (result.Data.Count > 0 && !param.IsSelfStok)  //非上传的货，计算价格
                    if (result.Data.Count > 0)  //非上传的货，计算价格
                    {
                        // CustomerInfo customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.CustomerID);//CustomerID值如存在，就按客户的价格；不存在就是团队的价格 
                        SysSettingInfo setting = GetSystemSetting(GoodsType.Diamond, 1, tttagKey);
                        if (setting == null)
                        {
                            return _msgInfo.Replace("#code", "false").Replace("#msg", "获取失败,请检查设置").Replace("#result", JsonConvert.SerializeObject(""));
                        }
                        //这里需要再取customer,
                        //customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.CustomerID);//CustomerID值如存在，就按客户的价格；不存在就是团队的价格 

                        //计算客户及用户看到的价格
                        //SystemSetting setting = new SystemSetting(GoodsType.Diamond);//裸钻
                        //SysSettingInfo setting = GetSystemSetting(GoodsType.Diamond, 1);
                        DiamondsPriceHandlers diamondspricehandlers = new DiamondsPriceHandlers();
                        foreach (var item in result.Data)
                        {
                            if (tttagKey.Contains("__")) //有二级key，则把一级得到的customer信息设置为原始信息开始计算
                            {
                                item.SourceDiscountReturn = item.CustomerDiscountReturn; //白钻用
                                item.SourceDolarPerGrain = item.CustomerDolarPerGrain; //彩钻用
                                //item.SourceDolarPerCarat = item.CustomerDolarPerCarat;
                            }
                            DiamondsPriceHandler.ComputePrice(tttagKey, item, setting, customerInfo, secondSn);//计算价格 
                        }
                    }
                    else
                    {
                         return _msgInfo.Replace("#code", "true").Replace("#msg", "没有任何记录").Replace("#result", JsonConvert.SerializeObject(result));
                    }
                    if (string.IsNullOrEmpty(open_Interface))
                    {
                        return _msgInfo.Replace("#code", "true").Replace("#msg", "获取库存成功").Replace("#result", JsonConvert.SerializeObject(result));
                    }
                    else  //开放接口返回
                    {
                        return _msgInfo.Replace("#code", "true").Replace("#msg", "获取库存成功").Replace("#result", AllPublic.ConvertAndFormatToJSONByOpenInterface(result));
                    }
                    #endregion
                }
                else
                {
                    return _msgInfo.Replace("#code", "false").Replace("#msg", "获取库存失败，请检查网络是否连接和接口是否正常").Replace("#result", JsonConvert.SerializeObject(""));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex, "", ex.Message + "==" + ex.StackTrace + "==" + ex.InnerException);
                //日志：ex.Message
                return _msgInfo.Replace("#code", "false").Replace("#msg", "获取库存失败:系统繁忙，请重试").Replace("#result", "");
            }
        }

        #endregion
        #region 裸钻现货管理（单个添加 修改 删除 批量调整 裸钻上下架）
        /// <summary>
        /// 导出上传模板
        /// </summary>
        /// <returns></returns>
        public string DownTemplate()
        {
            return AllPublic.DownTemplate("");
        }
        /// <summary>
        /// 新增裸钻
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public string AddDia(string addDiaParam)
        {
            addDiaParam = addDiaParam.Replace("BuyPurchaseSupplier", "PurchaseSupplier").Replace("PurchaseReturn", "OriginDiscountReturn").Replace("SourceDiscountReturn", "OriginDiscountReturn").Replace("SourceDolarPerGrain", "OriginUSDPerGrain").Replace("SourceDolarPerCarat", "OriginUSDPerCarat").Replace("BuyUSDPrice", "PurchaseUSDPerGrain").Replace("BuyRMBPrice", "PurchaseRMB ").Replace("PurchaseUserID", "PurchaseAgent").Replace("PurchaseExchangerate", "PurchaseExchange");
            logParam = addDiaParam;
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(addDiaParam);
            string tttagKey = CommonUrl.getURL(hsParam, addDiaParam, "零售一级新增裸钻");
            hsParam.Remove("TagKey"); 
            {
                //删除不用的参数
                hsParam.Remove("GoodsType");
                hsParam.Remove("ActiveIP");
                hsParam.Remove("OperationUserId");
                hsParam.Remove("HttpUrl");
                hsParam.Remove("Browser");
                hsParam.Remove("OpeartionSystem");
            }
            return CRetails.AddDia(hsParam, tttagKey);
        }

        /// <summary>
        /// 更新裸钻
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public string ModifyDia(string strParam)
        {
            var logParam = strParam;
            strParam = strParam.Replace("SourceDiscountReturn", "OriginDiscountReturn").Replace("SourceDolarPerGrain", "OriginUSDPerGrain").Replace("SourceDolarPerCarat", "OriginUSDPerCarat");
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam, "零售一级修改裸钻");
            {
                //删除不用的参数
                hsParam.Remove("GoodsType");
                hsParam.Remove("ActiveIP");
                hsParam.Remove("OperationUserId");
                hsParam.Remove("HttpUrl");
                hsParam.Remove("Browser");
                hsParam.Remove("OpeartionSystem");
            }
            hsParam.Remove("TagKey"); 
            
            return CRetails.ModifyDia(hsParam, tttagKey);
        }
        /// <summary>
        /// 删除裸钻
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public string DelDia(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam, "删除零售一级裸钻");
            hsParam.Remove("TagKey");
            return CRetails.DelDia(hsParam, tttagKey);
        }

        /// <summary>
        /// 批量修改裸钻
        /// </summary>
        /// <param name="batchUpdateDiaParam"></param>
        /// <returns></returns>
        public string BatchUpdateDia(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionBatchUpStockURL;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT);
        }
        /// <summary>
        ///  POST stocks/shelves/ 全部裸钻上架   ?IsFancy=1 全部彩钻上架
        /// </summary>
        /// <returns></returns>
        public string OnShelves(string param)
        {
            return AllPublic.OnShelves(param);
        }
        /// <summary>
        ///  Delete stocks/shelves/ 全部裸钻下架   ?IsFancy=1 全部彩钻下架
        /// </summary>
        /// <returns></returns>
        public string OffShelves(string param)
        {
            return AllPublic.OffShelves(param);
        }
        /// <summary>
        /// 裸钻库存批量修改（需要签名）
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public string BatchUpStockData(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionBatchUpStockURL;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT);
        }
        #endregion
        #region 裸钻购物车相关
        /// <summary>
        /// 获取购物车货品详情列表
        /// </summary>
        /// <param name="cartInfoParam"></param>
        /// <returns></returns>
        public string GetCartInfos(string cartInfoParam)
        {
            logParam = cartInfoParam;
            HashParam param = JsonConvert.DeserializeObject<HashParam>(cartInfoParam);
            string tttagKey = CommonUrl.getURL(param, cartInfoParam);
            if (param.ContainsKey("GoodsTypeID"))
            {

                var type = param["GoodsTypeID"].ToString().ToLower().Replace("diamonds", "1").Replace("parcels", "2").Replace("rings", "3")
                                                             .Replace("gems", "4").Replace("emeralds", "5").Replace("golds", "6");
                int goodsType = 0;
                int.TryParse(type, out goodsType);
                if (goodsType > 0)
                {
                    return SearchCartInfo(goodsType, cartInfoParam, tttagKey);
                }
                else
                    return CommonLog.MsgErrorInfo("无法预知的购物车类型");
            }
            else
                return CommonLog.MsgErrorInfo("缺少购物车类型参数");
        }
        /// <summary>
        /// 获取购物车列表
        /// </summary>
        /// <param name="catsParam"></param>
        /// <returns></returns>
        public string GetCarts(string cartsParam)
        {
            logParam = cartsParam;
            HashParam param = Json.Deserialize<HashParam>(cartsParam);
            string tttagKey = CommonUrl.getURL(param, cartsParam);
            //UserID
            try
            {
                IList<CartResult> cartInfos = YZ.GetDatabase(tttagKey).QueryForList<CartResult>("Cart.GetCarts", param);//本地购物车是否存在加入
                if (cartInfos != null && cartInfos.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(cartInfos));//返回Jason数据
                }
                else
                {
                    return CommonLog.MsgErrorInfo("购物车为空");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("获取失败,程序错误");
            }
        }
        public string GetCartsCount(string cartsParam)
        {
            logParam = cartsParam;
            HashParam param = Json.Deserialize<HashParam>(cartsParam);
            string tttagKey = CommonUrl.getURL(param, cartsParam);
            //UserID
            try
            {
                if (param.ContainsKey("CustomerID"))
                {
                    int count = YZ.GetDatabase(tttagKey).QueryForObject<int>("Cart.GetCartsCount", param);//本地购物车是否存在加入
                    return CommonLog.MsgSuccessInfo(count.ToString());
                }
                else
                    return CommonLog.MsgErrorInfo("参数不正确");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("获取失败,程序错误");
            }
        }
        /// <summary>
        /// 移出购物车
        /// </summary>
        /// <param name="removeFromCartParam"></param>
        /// <returns></returns>
        public string RemoveFromCart(string removeFromCartParam)
        {
            return DelAllCartByCustomerIdAndProductIds(removeFromCartParam, "InventoryIDs", "Cart.DeleteByInventoryIDs");
        }
        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <param name="addToCartParam"></param>
        /// <returns></returns>
        public string AddToCart(string addToCartParam)
        {
            logParam = addToCartParam;
            string tttagKey = CommonUrl.getURL(null, addToCartParam);
            //CustomerID,CartType,InventoryID 四参数(UserID)
            //templateJSON
            Cart param = Json.Deserialize<Cart>(addToCartParam);
            try
            {
                int totalSeconds;
                string signStr;
                var requestJson = "{\"ID\":" + param.GoodsID + ",\"useDict\":true}";
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestJson);//ID单个用ShotDic1 （非数组）
                var lastStr = MyHttpRequest.ShotDic1(objParams).ToString();//ID单个用ShotDic1 （非数组）
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 单个ID获取单条库存 (未下单的)
                PageList<InventoryInfoResult> _singleSellInvenoryInfo = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(  //序列化成 InventoryInfo
                        MyHttpRequest.ConvertToInventoryFormat(                //格式化库存的格式
                             MyHttpRequest.PostJSONByRequestParam(             //传递请求参数
                                new RequestInfo() { RequestJson = requestJson, RequestUrl = GlobalConfig.IUrl }  //获取请求参数
                                 , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST
                             )
                        )
                    );
                //数据仓库库存可用（远程）
                if (_singleSellInvenoryInfo.Data.Count > 0)
                {
                    InventoryInfo model_InventoryInfo = (InventoryInfo)_singleSellInvenoryInfo.Data[0];
                    if (model_InventoryInfo != null)
                    {
                        //param.SN = model_InventoryInfo.SN;
                        param.CreateTime = DateTime.Now;
                        CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.CustomerID);//CustomerID必传
                        if (customer != null)
                        {
                            param.UserID = customer.SalesUserID.Value;//业务ID
                        }
                        try
                        {
                            int addToCartResult = YZ.GetDatabase(tttagKey).Add(param);//加入购物车表
                            if (addToCartResult > 0)
                            {
                                return CommonLog.MsgSuccessInfo("加入购物车成功");
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("加入购物车失败，数据库添加操作错误，请重试");
                            }
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            return CommonLog.MsgErrorInfo("加入购物车失败，程序错误");
                        }
                    }
                }
                return CommonLog.MsgErrorInfo("加入购物车失败，已被抢购");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加入购物车失败,程序错误");
            }
        }
        /// <summary>
        /// 添加购物车(单个或多个)  --含事务
        /// </summary>
        /// <param name="multiAddToCartParam"></param>
        /// <returns></returns>
        public string MultiAddToCart(string multiAddToCartParam)
        {
            logParam = multiAddToCartParam;

            HashParam param = Json.Deserialize<HashParam>(multiAddToCartParam);
            string tttagKey = CommonUrl.getURL(param, multiAddToCartParam);
            //CustomerID,CartType,InventoryIDs 三参数(UserID)
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}"; //templateJSON
            int Failed = 0;  //失败条目
            int Successful = 0;//成功条目
            try
            {
                //先将字符转字符数组，然后将字符数组转整形数组
                string[] _inventoryIDs = param.GetString("InventoryIDs").TrimEnd(',').Split(',');//标准111,222,333,444 (兼容111,222,333,444,)
                int[] InventoryIDs = new int[_inventoryIDs.Length];
                int totalSeconds;
                string signStr;
                Cart cartInfo;
                CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(param.GetInt("CustomerID"));//CustomerID必传
                if (customer == null)
                {
                    return CommonLog.MsgErrorInfo("请先登录网站");
                }
                //检查裸钻是否被加入购物车
                if (!param.ContainsKey("GoodsTypeID"))
                {
                    return CommonLog.MsgErrorInfo("请选择商品");
                }
                for (int i = 0; i < _inventoryIDs.Length; i++)
                {
                    //检查裸钻是否被加入购物车
                    if (param.GetString("GoodsTypeID") == "1")
                    {
                        Hashtable hash = new Hashtable();
                        hash.Add("CustomerID", customer.CustomerID);
                        hash.Add("GoodsID", _inventoryIDs[i]);
                        cartInfo = YZ.GetDatabase(tttagKey).QueryForObject<Cart>("Cart.CheckExistsCart", hash);
                        if (cartInfo != null)
                        {
                            Failed++;//失败条目 
                            continue;
                        }
                    }

                    var requestJson = "{\"ID\":" + Convert.ToInt32(_inventoryIDs[i]) + ",\"useDict\":true}";//单个InventoryID (不能为空)
                    var guid = Guid.NewGuid().ToString();
                    var objParams = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestJson);//ID单个用ShotDic1 （非数组）
                    var lastStr = MyHttpRequest.ShotDic1(objParams);//ID单个用ShotDic1 （非数组）
                    MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                    //获取数据仓库库存（远程） 单个ID获取单条库存 (未下单的)
                    PageList<InventoryInfoResult> _singleSellInvenoryInfo = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(  //序列化成 InventoryInfo
                            MyHttpRequest.ConvertToInventoryFormat(                //格式化库存的格式
                                 MyHttpRequest.PostJSONByRequestParam(             //传递请求参数
                                    new RequestInfo() { RequestJson = requestJson, RequestUrl = GlobalConfig.IUrl }  //获取请求参数
                                     , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST
                                 )
                            )
                        );
                    //数据仓库库存可用（远程）
                    if (_singleSellInvenoryInfo.Data.Count > 0)
                    {
                        InventoryInfo model_InventoryInfo = (InventoryInfo)_singleSellInvenoryInfo.Data[0];
                        cartInfo = new Cart();
                        if (model_InventoryInfo != null)
                        {
                            cartInfo.GoodsTypeID = param.GetInt("GoodsTypeID").Value;
                            //_cartinfo.SN = model_InventoryInfo.SN;
                            cartInfo.CreateTime = DateTime.Now;//加入购物车时间
                            cartInfo.GoodsID = (int)model_InventoryInfo.ID;//库存号
                            cartInfo.CartType = Convert.ToInt32(param.GetString("CartType"));//来源
                            cartInfo.CustomerID = customer.CustomerID;//客户ID

                            using (ITransaction trans_addCart = YZ.GetTransaction(tttagKey))
                            {
                                int addToCartResult = trans_addCart.Add(cartInfo);//加入购物车表
                                if (addToCartResult > 0)
                                {
                                    try
                                    {
                                        trans_addCart.CommitTransaction(); //提交事务
                                        Successful++;//成功条目
                                    }
                                    catch (Exception)
                                    {
                                        trans_addCart.RollBackTransaction();//回滚事务
                                    }
                                }
                                else
                                {
                                    Failed++;//失败条目  
                                }
                            }
                        }
                    }
                }
                return _msgInfo.Replace("#code", "true").Replace("#msg", "加入购物车成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));//.TrimEnd(',')为数组 Substring为字符串 Failed.Substring(0, Failed.Length - 1)
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                //return _msgInfo.Replace("#code", "true").Replace("#msg", "程序错误：" );
                return CommonLog.MsgErrorInfo("程序错误：");
            }
        }
        #endregion
        #region 系统配置相关
        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="editSysSettingInfoParam"></param>
        /// <returns></returns>
        public string EditSysSettingInfo(string editSysSettingInfoParam)
        {
            logParam = editSysSettingInfoParam;
            string tttagKey = CommonUrl.getURL(null, editSysSettingInfoParam);
            //SysSettingID（必传）
            //templateJSON
            SysSettingInfo param = Json.Deserialize<SysSettingInfo>(editSysSettingInfoParam);
            try
            {
                param.UpdateTime = DateTime.Now;//上次更新时间
                using (ITransaction trans_editSysSetting = YZ.GetTransaction(tttagKey))
                {
                    int editSysSettingResult = trans_editSysSetting.Edit(param);
                    if (editSysSettingResult > 0)
                    {
                        try
                        {
                            trans_editSysSetting.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("修改设置成功");
                        }
                        catch (Exception)
                        {
                            trans_editSysSetting.RollBackTransaction();//回滚事务
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改设置失败，设置标识不存在");
                    }
                    return CommonLog.MsgErrorInfo("修改设置失败,请重试");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改客户失败，程序错误");
            }
        }
        /// <summary>
        /// 修改全局 11-10
        /// </summary>
        /// <param name="editNoticeParam"></param>
        /// <returns></returns>
        public string EditGlobal(string editGlobalParam)
        {
            logParam = editGlobalParam;
            string tttagKey = CommonUrl.getURL(null, editGlobalParam);
            //SysSettingID（必传）
            //templateJSON
            SysSettingInfo param = Json.Deserialize<SysSettingInfo>(editGlobalParam);
            try
            {
                param.UpdateTime = DateTime.Now;
                using (ITransaction trans_editGlobal = YZ.GetTransaction(tttagKey))
                {
                    int editGlobalResult = trans_editGlobal.Edit(param);
                    if (editGlobalResult > 0)
                    {
                        try
                        {
                            trans_editGlobal.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        catch (Exception e)
                        {
                            trans_editGlobal.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("修改失败:");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改失败，程序错误");
            }
        }
        /// <summary>
        /// 修改全局的币种  
        /// </summary>
        /// <param name="editNoticeParam"></param>
        /// <returns></returns>
        public string EditGlobalCurrency(string editGlobalParam)
        {
            logParam = editGlobalParam;
            string tttagKey = CommonUrl.getURL(null, editGlobalParam);
            //SysSettingID（必传）
            //templateJSON
            try
            {
                SysSettingInfo param = Json.Deserialize<SysSettingInfo>(editGlobalParam);
                if (param.CurrentSet > -1 && param.CurrentSet < 3) //0全部，1rmb，2usd
                {
                    try
                    {
                        int i = YZ.GetDatabase(tttagKey).Update("Syssetting.SetCurrency", param);
                        if (i > 0)
                            return CommonLog.MsgSuccessInfo("修改成功");
                        else
                            return CommonLog.MsgErrorInfo("修改成功");
                    }
                    catch (Exception e)
                    {
                        return CommonLog.MsgErrorInfo("修改失败:");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("保存失败，程序错误");
            }
        }
        /// <summary>
        /// 获取所有配置 
        /// </summary>
        /// <param name="sysSettingInfoParam"></param>
        /// <returns></returns>
        public string GetSysSettingInfo(string param)
        {
            //templateJSON
            try
            {
                logParam = param;
                string tttagKey = CommonUrl.getURL(null, param);
                SysSettingInfo setting = YZ.GetDatabase(tttagKey).QueryForObject<SysSettingInfo>("Syssetting.GetLooseSetting", null);
                if (setting != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(setting));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("加载失败");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败");
            }
        }
        /// <summary>
        /// 获取全局售出汇率
        /// </summary>
        /// <returns></returns>
        public string GetRate(string getRateParam)
        {
            logParam = getRateParam;
            HashParam param = Json.Deserialize<HashParam>(getRateParam);
            string tttagKey = CommonUrl.getURL(param, getRateParam);
            //SysSettingID
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"data\":#result}"; //templateJSON
            try
            {
                SysSettingInfo setting = YZ.GetDatabase(tttagKey).QueryForObject<SysSettingInfo>("Syssetting.GetRate", param);//SysSettingID
                if (setting != null)
                {
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "获取全局设置成功").Replace("#result", JsonConvert.SerializeObject(setting));
                }
                else
                {
                    return _msgInfo.Replace("#code", "false").Replace("#msg", "获取全局设置失败,无标识").Replace("#result", JsonConvert.SerializeObject(""));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 获取采购汇率
        /// </summary>
        /// <returns></returns>
        public string GetExchangeRate(string param)
        {
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"data\":#result}"; //templateJSON
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            try
            {
                SysSettingInfo setting = YZ.GetDatabase(tttagKey).QueryForObject<SysSettingInfo>("Syssetting.GetRate", 1);//SystemID=1裸钻设置
                if (setting != null)
                {
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "获取成功").Replace("#result", JsonConvert.SerializeObject(setting));
                }
                else
                {
                    return _msgInfo.Replace("#code", "false").Replace("#msg", "获取失败:请检查配置标识").Replace("#result", JsonConvert.SerializeObject(""));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误：");
            }
        }
        /// <summary>
        /// 单个全局
        /// </summary>
        /// <param name="noticeInfoParam"></param>
        /// <returns></returns>
        public string GetSettingInfo(string settingInfoParam)
        {
            logParam = settingInfoParam;
            string tttagKey = CommonUrl.getURL(null, settingInfoParam);
            //templateJSON
            SysSettingInfo param = Json.Deserialize<SysSettingInfo>(settingInfoParam);
            try
            {
                SysSettingInfo settingInfo = YZ.GetDatabase(tttagKey).Get<SysSettingInfo>(param);
                if (settingInfo != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(settingInfo));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 所有全局设置 11-10
        /// </summary>
        /// <param name="getGlobalsParam"></param>
        /// <returns></returns>
        public string GetGlobals(string getGlobalsParam)
        {
            logParam = getGlobalsParam;
            string tttagKey = CommonUrl.getURL(null, getGlobalsParam);

            Hashtable param = new Hashtable();
            if (getGlobalsParam != "")
            {
                param = MyHashtable.NewHashtable(JsonConvert.DeserializeObject<Hashtable>(getGlobalsParam));
            }
            //参数可全空
            //HashParam param = Json.Deserialize<HashParam>(getGlobalsParam);//PageParam是个坑 9-6
            try
            {
                IList<SysSettingInfo> _settingInfo = YZ.GetDatabase(tttagKey).QueryForList<SysSettingInfo>("Syssetting.GetList", param);//IList 11-10
                if (_settingInfo != null && _settingInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_settingInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("\"没有任何记录\"");//空
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 返回更新日志 9-29
        /// </summary>
        /// <returns></returns>
        public string UpdateLog()
        {
            return AllPublic.UpdateLog("");
        }
        /// <summary>
        /// 更新本地报价XML 10-9
        /// </summary>
        /// <returns></returns>
        public string UpdateRapXml()
        {
            //templateJSON
            XmlDocument xmldoc = new XmlDocument();
            string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\diamond_all_price.xml";//本地xml路径
            //查询查宝网xml
            XmlDocument xmldoc_checkgems = new XmlDocument();
            try
            {
                //放配置文件中，到时xml改路径不用改程序，要求xml一样就行
                var url = ConfigurationManager.AppSettings["PricexmlUrlByCheckgems"]; //http://www.checkgems.com/calc/pricelist?code=web
                xmldoc_checkgems.Load(url);
                xmldoc.Load(path);
                XmlNodeList xnlPrice = xmldoc_checkgems.SelectNodes("/items/item");
                //接口报价表内容是否正确
                if (xnlPrice.Count > 0)
                {
                    var version = xmldoc_checkgems.SelectSingleNode("/items/version").InnerText;  //查宝网  //xmldoc_checkgems.InnerText 也可获取
                    var version2 = xmldoc.SelectSingleNode("/items/version").InnerText;  //本地
                    if (version != version2) //不一样 更新文件
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create))
                        {
                            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                            sw.Write(xmldoc_checkgems.InnerXml);
                            sw.Close();
                        }
                        xmldoc.Load(path); //重新载入
                        return CommonLog.MsgSuccessInfo("更新成功");
                    }
                    else
                    {
                        return CommonLog.MsgSuccessInfo("已是最新");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("接口报价表内容错误，正确示例<item key='' value=''/>");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("更新报价表失败");
            }
        }
        #endregion
        #region  格式化相关
        //形状格式化
        public string ShapeFormat(int shapeValue)
        {
            if (shapeValue == 1)
            {
                return "圆形";
            }
            else if (shapeValue == 2)
            {
                return "公主方";
            }
            else if (shapeValue == 3)
            {
                return "祖母绿";
            }
            else if (shapeValue == 4)
            {
                return "雷迪恩";
            }
            else if (shapeValue == 5)
            {
                return "椭圆形";
            }
            else if (shapeValue == 6)
            {
                return "梨形";
            }
            else if (shapeValue == 7)
            {
                return "马眼形";
            }
            else if (shapeValue == 8)
            {
                return "心形";
            }
            else if (shapeValue == 9)
            {
                return "三角形";
            }
            else if (shapeValue == 10)
            {
                return "垫形";
            }
            else if (shapeValue == 11)
            {
                return "其他";
            }
            else
            {
                return "" + shapeValue;
            }
        }
        //形状格式化
        public int GetShape(string shapeValue)
        {
            logParam = shapeValue;
            string tttagKey = CommonUrl.getURL(null, shapeValue);
            if (shapeValue == "圆形")
            {
                return 1;
            }
            else if (shapeValue == "公主方")
            {
                return 2;
            }
            else if (shapeValue == "祖母绿")
            {
                return 3;
            }
            else if (shapeValue == "雷迪恩")
            {
                return 4;
            }
            else if (shapeValue == "椭圆形")
            {
                return 5;
            }
            else if (shapeValue == "梨形")
            {
                return 6;
            }
            else if (shapeValue == "马眼形")
            {
                return 7;
            }
            else if (shapeValue == "心形")
            {
                return 8;
            }
            else if (shapeValue == "三角形")
            {
                return 9;
            }
            else if (shapeValue == "垫形")
            {
                return 10;
            }
            else if (shapeValue == "其他")
            {
                return 11;
            }
            else
            {
                return 0;
            }
        }
        //订单类型格式化
        public string OrderTypeFormat(int userId = 0)
        {
            if (userId == 0)
            {
                return "客主";
            }
            else if (userId > 0)
            {
                return "代客";
            }
            else
            {
                return "" + userId;
            }
        }
        //订单状态格式化(团队)
        public string OrderStatusFormat(int? orderStatusValue)
        {
            if (orderStatusValue == 1)
            {
                return "待采购";
            }
            else if (orderStatusValue == 2)
            {
                return "待到货";
            }
            else if (orderStatusValue == 3)
            {
                return "待出货";
            }
            else if (orderStatusValue == 4)
            {
                return "已出货";
            }
            else if (orderStatusValue == 5)
            {
                return "已作废";
            }
            else if (orderStatusValue == 6)
            {
                return "已自留";
            }
            else if (orderStatusValue == 7)
            {
                return "已退回";
            }
            else
            {
                return "" + orderStatusValue;
            }
        }
        //订单状态格式化(客户)
        public string CustomerOrderStatusFormat(int? orderStatusValue)
        {
            if (orderStatusValue == 1)
            {
                return "下单成功";
            }
            else if (orderStatusValue == 2)
            {
                return "定购成功";
            }
            else if (orderStatusValue == 3)
            {
                return "到货成功";
            }
            else if (orderStatusValue == 4)
            {
                return "交货成功";
            }
            else if (orderStatusValue == 5)
            {
                return "作废成功";
            }
            else if (orderStatusValue == 6)
            {
                return "退货成功";
            }
            else if (orderStatusValue == 7)
            {
                return "退货成功";
            }
            else
            {
                return "" + orderStatusValue;
            }
        }
        /// 付款状态格式化
        public string ReceiptStatusFormat(int? paymentstatusValue)
        {
            if (paymentstatusValue == 0)
            {
                return "未付";
            }
            else if (paymentstatusValue == 1)
            {
                return "已付";
            }
            else
            {
                return "" + paymentstatusValue;
            }
        }
        //收款状态格式化
        public string PaymentStatusFormat(int? paymentstatusValue)
        {
            if (paymentstatusValue == 0)
            {
                return "未收";
            }
            else if (paymentstatusValue == 1)
            {
                return "已收";
            }
            else
            {
                return "" + paymentstatusValue;
            }
        }
        //账户格式化 12-3
        public string PaymentModelFormat(string paymentModelValue)
        {
            logParam = paymentModelValue;
            string tttagKey = CommonUrl.getURL(null, paymentModelValue);
            if (paymentModelValue == "1")
            {
                return "支付宝";
            }
            else if (paymentModelValue == "2")
            {
                return "微信";
            }
            else if (paymentModelValue == "3")
            {
                return "中行";
            }
            else if (paymentModelValue == "4")
            {
                return "农行";
            }
            else if (paymentModelValue == "5")
            {
                return "工行";
            }
            else if (paymentModelValue == "6")
            {
                return "建行";
            }
            else if (paymentModelValue == "7")
            {
                return "民生";
            }
            else if (paymentModelValue == "8")
            {
                return "平安";
            }
            else if (paymentModelValue == "9")
            {
                return "优惠额";
            }
            else if (paymentModelValue == "10")
            {
                return "手续费";
            }
            else if (paymentModelValue == "11")
            {
                return "现金";
            }
            else
            {
                return paymentModelValue;
            }
        }
        //充值类型格式化 12-3
        public string OperationModelFormat(int? operationModelValue)
        {
            if (operationModelValue == 1)
            {
                return "已充值";
            }
            else if (operationModelValue == 0)
            {
                return "待充值";
            }
            else if (operationModelValue == -1)
            {
                return "已作废";
            }
            else
            {
                return "待查 " + operationModelValue;
            }
        }
        //交易类型Type 12-10
        public string TypeFormat(int? typeValue)
        {
            if (typeValue == 1)
            {
                return "收入";
            }
            else if (typeValue == 3)
            {
                return "定金";
            }
            else if (typeValue == 2)
            {
                return "支出";
            }
            else if (typeValue == 4)
            {
                return "提现";
            }
            else
            {
                return "" + typeValue;
            }
        }
        //账户类型Account
        public string AccountFormat(int? accountValue)
        {
            if (accountValue == 1)
            {
                return "工商";
            }
            else if (accountValue == 2)
            {
                return "建设";
            }
            else if (accountValue == 3)
            {
                return "中行";
            }
            else if (accountValue == 4)
            {
                return "农业";
            }
            else if (accountValue == 5)
            {
                return "支付宝";
            }
            else if (accountValue == 6)
            {
                return "微信";
            }
            else if (accountValue == 7)
            {
                return "HK-$";
            }
            else if (accountValue == 8)
            {
                return "现金";
            }
            else
            {
                return "" + accountValue;
            }
        }
        //流水状态Status
        public string StatusFormat(int? statusValue)
        {
            if (statusValue == 1)
            {
                return "已审核";
            }
            else if (statusValue == 0)
            {
                return "待审核";
            }
            else if (statusValue == -1)
            {
                return "已作废";
            }
            else
            {
                return "" + statusValue;
            }
        }
        #endregion
        #region  流上传
        /// <summary>
        /// WCF服务端上传文件File到数据中心
        /// </summary>
        /// <returns></returns>
        public UpFileResult OldUploadFile(FileUploadMessage request)
        {
            UpFileResult result = new UpFileResult();
            try
            {
                //上传
                string guid = Guid.NewGuid().ToString();
                Dictionary<string, string> param = new Dictionary<string, string>();
                string stateid = "1"; //上传模式（0覆盖 1追加） 
                if (HttpContext.Current.Request.Url.Query.Contains("?addType=1") || HttpContext.Current.Request.Url.Query.Contains("?addType=0"))
                {
                    string paramStr = HttpContext.Current.Request.Url.Query.Replace("?", "");
                    string[] paramStrSplit = paramStr.Split('&');
                    stateid = paramStrSplit[0].Split('=')[1]; 
                }
                else
                {
                    if (HttpRuntime.Cache.Get("StateId") != null)
                    {
                        stateid = HttpRuntime.Cache.Get("StateId").ToString();
                    }
                }
                param["is_append"] = stateid.ToString(); //是否已追加的方式导入，如果为0则清空以前的库存，默认1
                var RequestUrl = GlobalConfig.TransmissionUpStockURL + "files/?is_append=" + stateid.ToString();
                //排序参数
                StringBuilder sbStr = MyHttpRequest.ShotDic(param);
                int totalSeconds;
                string signStr;
                //签名
                MyHttpRequest.SignByParams(guid, sbStr.ToString(), request.key, out totalSeconds, out signStr);
                RequestInfo ri = new RequestInfo()
                {
                    RequestJson = JsonConvert.SerializeObject(param),
                    RequestUrl = GlobalConfig.TransmissionUpStockURL + "files/?is_append=" + stateid.ToString()   
                };
                //发送带签名的参数
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");//保持长连接
                using (var content = new MultipartFormDataContent())
                {
                    var fileContent = new StreamContent(request.FileData);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = request.FileName, Name = "file_data" };
                    content.Add(fileContent);
                    content.Headers.Add("UUID", guid);
                    content.Headers.Add("Auth", signStr);
                    content.Headers.Add("Time", totalSeconds.ToString());
                    //提交数据中心
                    var responseJson = httpClient.PostAsync(RequestUrl, content)
                     .Result.Content.ReadAsStringAsync().Result;
                    result.Message = @responseJson;//上传结果
                    if (@responseJson.Contains("result\":\"true") || JsonConvert.DeserializeObject<HashParam>(@responseJson).GetString("result").ToLower() == "true")
                    {
                        result.IsSuccess = true;
                    }
                    else
                        result.IsSuccess = false;
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                result.Message = "服务端上传到数据中心失败";
                result.IsSuccess = false;
                Logger.Warn(typeof(Retail), "服务端上传到数据中心失败");
            }
            return result;
        }
        /// <summary>
        /// WCF服务端上传文件File到数据中心(多级接收：一级客户端，二级服务)  2017-02-06
        /// </summary>
        /// <returns></returns>
        public UpFileResult UploadFile(FileUploadMessage request)
        {
            UpFileResult result = new UpFileResult();
            try
            {
                request.FileName.Replace("addType", "is_append");
                var requeURL = "";
                if (request.GoodsType == "stock")
                {
                    requeURL = GlobalConfig.TransmissionUpStockURL + "files/";
                }
                else if (request.GoodsType == "inlays")
                {
                    requeURL = GlobalConfig.TransmissionInlaysImportUrl;
                }
                else if (request.GoodsType == "parcels")
                {
                    requeURL = GlobalConfig.TransmissionParcelsImportUrl;
                }
                else if (request.GoodsType == "emeralds")
                {
                    requeURL = GlobalConfig.TransmissionEmeraldsImportUrl;
                }
                else if (request.GoodsType.ToLower() == "inlaysettings")
                {
                    requeURL = GlobalConfig.TransmissionInlaySettingsImportUrl;
                }
                result = CRetails.UpLoadPart2(request, requeURL, "");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                result.Message = "服务端上传到数据中心失败";
                result.IsSuccess = false;
                Logger.Warn(typeof(Retail), "服务端上传到数据中心失败");
            }
            return result;
        }

        /// <summary>
        /// WCF服务端上传图片Image到数据中心
        /// </summary>
        /// <param name="imageParam"></param>
        /// <returns></returns>
        public UpFileResult UploadImage(FileUploadMessage imageParam)
        {
            //#msg 和"#msg" 
            UpFileResult result = new UpFileResult();
            try
            {
                var type = imageParam.FileName.Split('|')[1];
                var imageName = imageParam.FileName.Split('|')[0];
                var RequestUrl = string.Format(GlobalConfig.TransmissionImageUploadUrl, type, imageName);
                //上传
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                //签名
                MyHttpRequest.SignByParams(guid, "", imageParam.key, out totalSeconds, out signStr);
                RequestInfo ri = new RequestInfo()
                {
                    RequestUrl = RequestUrl // secondSn,有可能为二级提交
                };
                //发送带签名的参数
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");//保持长连接
                using (var content = new MultipartFormDataContent())
                {
                    var fileContent = new StreamContent(imageParam.FileData);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = imageName, Name = "file_data" };
                    content.Add(fileContent);
                    content.Headers.Add("UUID", guid);
                    content.Headers.Add("Auth", signStr);
                    content.Headers.Add("Time", totalSeconds.ToString());
                    //提交数据中心
                    var responseJson = httpClient.PostAsync(RequestUrl, content)
                     .Result.Content.ReadAsStringAsync().Result;
                    result.Message = @responseJson;//上传结果
                    result.IsSuccess = JsonConvert.DeserializeObject<HashParam>(@responseJson).GetBool("result");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                result.Message = "上传出错:程序错误";
                result.IsSuccess = false;
                return result;
            }
        }
        /// <summary>
        /// WCF服务端上传图片Image到数据中心
        /// </summary>
        /// <param name="imageParam"></param>
        /// <returns></returns>
        public UpFileResult UploadImage(ImageUploadMessage imageParam)
        {
            //#msg 和"#msg"
            UpFileResult result = new UpFileResult();
            var RequestUrl = "";
            if (imageParam.ImageDatas.Length == 0)
            {
                result.Message = "{\"msg\": \"noImgUpload\", \"successes\": [], \"result\": false, \"failures\": []}";//上传结果
                result.IsSuccess = false;
            }
            else
            {
                try
                {
                    var type = imageParam.TypeName;
                    if (imageParam.type == "img")
                        RequestUrl = string.Format(GlobalConfig.TransmissionImageUploadUrl, type, "");
                    else if (imageParam.type == "video")
                        RequestUrl = string.Format(GlobalConfig.TransmissionVideoUploadUrl, type, "");
                    //上传
                    string guid = Guid.NewGuid().ToString();
                    int totalSeconds;
                    string signStr;
                    //签名
                    MyHttpRequest.SignByParams(guid, "", imageParam.key, out totalSeconds, out signStr);
                    RequestInfo ri = new RequestInfo()
                    {
                        RequestUrl = RequestUrl // secondSn,有可能为二级提交
                    };
                    //发送带签名的参数
                    var httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");//保持长连接
                    using (var content = new MultipartFormDataContent())
                    {
                        for (int i = 0; i < imageParam.ImageDatas.Count(); i++)
                        {
                            //var fileContent = new StreamContent(imageParam.ImageDatas[i].ImageData);
                            var fileContent = new StreamContent(new MemoryStream(imageParam.ImageDatas[i].ImageData));
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = FormatFileName(imageParam.ImageDatas[i].FileName), Name = "file_data" };
                            content.Add(fileContent);
                        }
                        content.Headers.Add("UUID", guid);
                        content.Headers.Add("Auth", signStr);
                        content.Headers.Add("Time", totalSeconds.ToString());
                        //提交数据中心
                        var responseJson = httpClient.PostAsync(RequestUrl, content)
                         .Result.Content.ReadAsStringAsync().Result;
                        result.Message = @responseJson; //上传结果
                        result.IsSuccess = JsonConvert.DeserializeObject<HashParam>(@responseJson).GetBool("result");
                    }
                }
                catch (Exception ex)
                {
                    GetMethodInfoAndWriteLogs(ex);
                    result.Message = "上传出错:程序错误";
                    result.IsSuccess = false;
                    return result;
                }
            }
            return result;
        }
        public string FormatFileName(string name)
        {
            logParam = name; 
            if (name.LastIndexOf(".") > -1)
            {
                name = DateTime.Now.Ticks.ToString() + (name.Substring(name.LastIndexOf("."), name.Length - name.LastIndexOf(".")));
            }
            return name;
        }
        #endregion
        #region 用户活跃度
        /// <summary>
        /// 活跃时间
        /// </summary>
        /// <returns></returns>
        public string GetActiveTime(string activeTimeParam)
        {
            logParam = activeTimeParam;
            HashParam param = Json.Deserialize<HashParam>(activeTimeParam); //Deserialize 反序列化
            string tttagKey = CommonUrl.getURL(param, activeTimeParam);
            IList<HashResult> days = YZ.GetDatabase(tttagKey).QueryForList<HashResult>("Address.GetDay", param);//2016-11-17 10:07:13
            IList<HashResult> months = YZ.GetDatabase(tttagKey).QueryForList<HashResult>("Address.GetMonth", param);
            var activeResult = new Dictionary<string, IList<HashResult>>();
            activeResult.Add("months", months);
            activeResult.Add("days", days);
            var str = JsonConvert.SerializeObject(activeResult);
            return str;
        }
        /// <summary>
        /// 活跃地区
        /// </summary>
        /// <returns></returns>
        public string GetActiveArea(string activeAreaParam)
        {
            logParam = activeAreaParam;
            HashParam param = Json.Deserialize<HashParam>(activeAreaParam); //Deserialize 反序列化
            string tttagKey = CommonUrl.getURL(param, activeAreaParam);
            IList ips = YZ.GetDatabase(tttagKey).QueryForList("Address.GetArea", param);
            Dictionary<string, int> addrsInfo = new Dictionary<string, int>();
            foreach (var ip in ips)
            {
                if (ip != null && ip.ToString().Length > 6) //min 7
                {
                    var addr = getAddrByIP(ip.ToString());
                    var addrs = addr.Split('\t');
                    addr = addrs[2]; //中国广东广州(取广州) 
                    if (addr == "")
                    {
                        addr = addrs[1]; //中国香港(取香港) 美国美国(取美国)
                    }
                    addr = addr == "resultOffSet too small" ? "未知" : addr == "共享地址" ? "未知" : addr == "CLOUDFLARE" ? "未知" : addr;
                    if (addrsInfo.ContainsKey(addr))
                    {
                        addrsInfo[addr]++;
                    }
                    else
                    {
                        addrsInfo.Add(addr, 1);
                    }
                }
            }
            addrsInfo = addrsInfo.OrderByDescending(t => t.Value).ToDictionary(a => a.Key, b => b.Value);
            return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(addrsInfo));
        }
        /// <summary>
        /// 根据活跃IP得到活跃地区
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public string getAddrByIP(string ip)
        {
            logParam = ip;
            string tttagKey = CommonUrl.getURL(null, ip);
            DataHandler ips = new DataHandler(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "au/ikvm_data\\db.dat"));
            var ipStr = ips.findGeography(ip);
            return ipStr;
        }
        #endregion
        #region 各种统计相关
        /// <summary>
        /// 统计每年每月的订单 9-22
        /// </summary>
        /// <param name="orderNumberParam"></param>
        /// <returns></returns>
        public string OrderMonth(string orderMonthParam)
        {
            logParam = orderMonthParam;
            HashParam param = Json.Deserialize<HashParam>(orderMonthParam);//客户ID 团队ID 
            string tttagKey = CommonUrl.getURL(param, orderMonthParam);
            //templateJSON
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetOrderMonth", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("统计为0");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("统计失败");
            }
        }
        /// <summary>
        /// 订单个数统计 、各订单状态卖出RMB和买入美金统计 9-22
        /// </summary>
        /// <returns></returns>
        public string OrderNumber(string orderNumberParam)
        {
            logParam = orderNumberParam;
            HashParam param = Json.Deserialize<HashParam>(orderNumberParam);//客户ID 团队ID 
            string tttagKey = CommonUrl.getURL(param, orderNumberParam);
            //templateJSON
            try
            {
                IList<HashParam> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<HashParam>("Order.GetOrderNumber", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("无法统计,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("订单统计加载失败");
            }
        }
        /// <summary>
        /// 结算订单状态统计 11-2
        /// </summary>
        /// <param name="orderNumberParam"></param>
        /// <returns></returns>
        public string SettleOrderNumber(string settleOrderNumberParam)
        {
            logParam = settleOrderNumberParam;
            HashParam param = Json.Deserialize<HashParam>(settleOrderNumberParam);//客户ID 团队ID 
            string tttagKey = CommonUrl.getURL(param, settleOrderNumberParam);
            //templateJSON
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetOrderNumber", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("无法统计,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("订单统计加载失败");
            }
        }
        /// <summary>
        /// 结算订单支付状态统计 11-2
        /// </summary>
        /// <param name="orderPaymentStatusNumberParam"></param>
        /// <returns></returns>
        public string SettleOrderPaymentStatusNumber(string settleOrderPaymentStatusNumberParam)
        {
            logParam = settleOrderPaymentStatusNumberParam;
            HashParam param = Json.Deserialize<HashParam>(settleOrderPaymentStatusNumberParam);//客户ID 团队ID 
            string tttagKey = CommonUrl.getURL(param, settleOrderPaymentStatusNumberParam);
            //templateJSON
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetSettleOrderPaymentStatusNumber", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("无法统计,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("订单统计加载失败");
            }
        }
        /// <summary>
        /// 订单支付状态统计
        /// </summary>
        /// <param name="orderNumberParam"></param>
        /// <returns></returns>
        public string OrderPaymentStatusNumber(string orderPaymentStatusNumberParam)
        {
            logParam = orderPaymentStatusNumberParam;
            HashParam param = Json.Deserialize<HashParam>(orderPaymentStatusNumberParam);//客户ID 团队ID 
            string tttagKey = CommonUrl.getURL(param, orderPaymentStatusNumberParam);
            //templateJSON
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetOrderPaymentStatusNumber", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("无法统计,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("订单统计加载失败");
            }
        }
        //柱状图 业务每月销售额 9-23 test
        public string TestHigh(string testParam)
        {
            logParam = testParam;
            HashParam param = Json.Deserialize<HashParam>(testParam);
            string tttagKey = CommonUrl.getURL(param, testParam);
            //templateJSON
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetOrderNumber", param);
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("订单统计为0.");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("订单统计加载失败");
            }
        }

        /// <summary>
        /// 充值个数统计
        /// </summary>
        /// <returns></returns>
        public string ChargeNumber(string chargeNumberParam)
        {
            logParam = chargeNumberParam;
            HashParam param = Json.Deserialize<HashParam>(chargeNumberParam);
            string tttagKey = CommonUrl.getURL(param, chargeNumberParam);
            //templateJSON
            try
            {
                IList<RechargeResult> _chargeInfo = YZ.GetDatabase(tttagKey).QueryForList<RechargeResult>("Recharge.GetChargeNumber", param);
                if (_chargeInfo != null && _chargeInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_chargeInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("客户充值为0.");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("客户充值加载失败");
            }
        }
        /// <summary>
        /// 购物车个数统计
        /// </summary>
        /// <param name="chargeNumberParam"></param>
        /// <returns></returns>
        public string CartNumber(string cartNumberParam)
        {
            logParam = cartNumberParam;
            HashParam param = Json.Deserialize<HashParam>(cartNumberParam);
            string tttagKey = CommonUrl.getURL(param, cartNumberParam);
            //templateJSON
            try
            {
                IList<CartResult> _cartsInfo = YZ.GetDatabase(tttagKey).QueryForList<CartResult>("Cart.GetCartNumber", param);
                if (_cartsInfo != null && _cartsInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_cartsInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("购物车统计为0.");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("购物车统计加载失败");
            }
        }
        /// <summary>
        /// 订单周报表 2017-02-18
        /// </summary>
        /// <returns></returns>
        public string OrderReport(string reportParam)
        {
            logParam = reportParam;
            string tttagKey = CommonUrl.getURL(null, reportParam);
            //templateJSON
            PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(reportParam);
            try
            {
                IList<HashParam> list = new List<HashParam>();//IList的Param
                var cTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")); //当前
                const int wDay = 7;//周起止时间
                //const int allWeek = 3; //一共拿4周数据
                int allWeek = param.pageSize; //一共拿PageSize+1周数据
                int cWeek = Convert.ToInt32(cTime.DayOfWeek);//星期几 
                decimal lastWeekUSD = 0, lastWeekRate = 0;
                for (int i = allWeek; i >= 0; i--)
                {
                    param.SArrivalTime = cTime.AddDays((1 - cWeek) - (i * wDay));   //起
                    param.EArrivalTime = param.SArrivalTime.Value.AddDays(wDay).AddSeconds(-1); //拿到最后一秒
                    if (i == allWeek) // 第一次加载历史数据 -只会执行一次
                    {
                        var startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).AddYears(-3);//test
                        var endTime = param.SArrivalTime;
                        var pageParam = new { SArrivalTime = startTime, EArrivalTime = endTime };
                        var tempParam = Json.Deserialize<PageParamOfOrder>(JsonConvert.SerializeObject(pageParam));
                        var historyData = GetHistoryInfo(tempParam, tttagKey);//历史数据
                        lastWeekUSD = historyData.GetDecimal("RestUSD").Value;
                        lastWeekRate = historyData.GetDecimal("WeekPurchaseExchange").Value;
                    }
                    list.Add(GetInfoByWeek(tttagKey, param, ref lastWeekUSD, ref lastWeekRate));//加入每周数据
                }
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误：");
            }
        }
        //得到单周的数据
        private static HashParam GetInfoByWeek(string tttagKey, PageParamOfOrder param1, ref decimal lastWeekUSD, ref decimal lastWeekRate)
        {
            //RestUSD 周剩余美金
            // WeekPurchaseExchange 周采购汇率  
            // WeekAvgExchange 周平均汇率 
            // WeekExUSD 周兑换美金
            // WeekNum 周美金结算订单数
            // WeekUSD 周总美金
            // WeekRMB 周总人民币
            // WeekExpense 周取货费用
            decimal? RestUSD = 0, WeekUSD = 0, WeekRMB = 0, WeekAvgExchange = 0, WeekPurchaseExchange = 0, WeekNum = 0, WeekExpense = 0;
            decimal? totalUSD2 = 0,//周应支付金额
                    totalUSD3 = 0;//周总已兑换美金
            HashParam param2 = new HashParam();
            //本周全部订单
            #region
            IList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrders", param1);//本周
            if (_ordersInfo != null && _ordersInfo.Count > 0)
            {
                foreach (var item in _ordersInfo)
                {
                    //定货
                    if (item.Supplier.ToLower() != tttagKey)
                    {
                        //美金结算
                        if (item.CurType == 2)
                        {
                            WeekUSD += item.PriceUSD;//周总美金
                            WeekNum++;//周美金结算订单数
                        }
                        else
                        {
                            WeekRMB += item.PurchaseRMB;//周总人民币
                        }
                    }
                    else
                    {
                        //现货                        
                    }
                }
                //WeekExpense = WeekUSD * Convert.ToDecimal(0.004);//周取货费用
                WeekExpense = WeekUSD * Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["BaseFreight"]);//周取货费用  2017-02-23              
            }
            #endregion
            //本周兑换记录
            #region
            IList<ExchangeResult> _exchangeInfo = YZ.GetDatabase(tttagKey).QueryForList<ExchangeResult>("Exchange.GetExchanges", param1);//本周兑换记录
            if (_exchangeInfo != null && _exchangeInfo.Count > 0)
            {
                foreach (var item in _exchangeInfo)
                {
                    totalUSD2 += item.Exchange * item.Amount;//总应支付金额
                    totalUSD3 += item.Amount;//总已兑换美金
                }
                WeekAvgExchange = totalUSD2 / totalUSD3;//周平均汇率
            }
            #endregion
            //本周订单买入$ 和 个数
            #region
            param2["WeekUSD"] = WeekUSD;
            param2["WeekNum"] = WeekNum;
            param2["WeekExpense"] = WeekExpense;
            param2["WeekAvgExchange"] = WeekAvgExchange;
            param2["WeekExUSD"] = totalUSD3;//周兑换美金
            param2["EArrivalTime"] = param1.EArrivalTime.Value.ToShortDateString();
            param2["SArrivalTime"] = param1.SArrivalTime.Value.ToShortDateString();
            //本周剩余美金 = （本周兑换美金 + 上周剩余美金） -（本周取货花费 + 本周取货产生的带货费用）
            //param2["RestUSD"] = (totalUSD3 + 0) - WeekUSD - WeekExpense;//周剩余美金
            RestUSD = (totalUSD3 + lastWeekUSD) - (WeekUSD + WeekExpense);//（上周剩余+本周兑换）-本周开销
            param2["RestUSD"] = RestUSD;//周剩余美金
            //本周新汇率 = ( (上周剩余美金 * 上周平均汇率) + (本周兑换美金 * 本周平均汇率) ) / (上周剩余美金 + 本周兑换美金)
            //WeekPurchaseExchange = ((0 * 0) + (totalUSD3 * WeekAvgExchange)) / (0 + totalUSD3);//周采购汇率 -首次
            if (lastWeekUSD + totalUSD3 > 0)
            {
                WeekPurchaseExchange = (Convert.ToDecimal(lastWeekUSD * lastWeekRate) + (totalUSD3 * WeekAvgExchange)) / (lastWeekUSD + totalUSD3);//周采购汇率
            }
            else
            {
                WeekPurchaseExchange = 0;
            }
            param2["WeekPurchaseExchange"] = WeekPurchaseExchange;//周采购汇率
            #endregion
            if (RestUSD.Value < 0)
            {
                lastWeekUSD = 0; //存储给下次使用
            }
            else
            {
                lastWeekUSD = RestUSD.Value; //存储给下次使用
            }
            lastWeekRate = WeekPurchaseExchange.Value;//存储给下次使用
            return param2;
        }
        //某日期得到以前的数据
        private static HashParam GetHistoryInfo(PageParamOfOrder param1, string tttagKey)
        {
            decimal? RestUSD = 0, WeekUSD = 0, WeekRMB = 0, WeekAvgExchange = 0, WeekNum = 0, WeekExpense = 0;
            decimal? totalUSD2 = 0,//周应支付金额
                    totalUSD3 = 0;//周总已兑换美金
            HashParam param2 = new HashParam();
            //某日期以前全部订单
            #region
            IList<OrderInfo> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrders", param1);//本周
            if (_ordersInfo != null && _ordersInfo.Count > 0)
            {
                foreach (var item in _ordersInfo)
                {
                    //定货
                    if (item.Supplier.ToLower() != tttagKey)
                    {
                        //美金结算
                        if (item.CurType == 2)
                        {
                            WeekUSD += item.PriceUSD;//周总美金
                            WeekNum++;//周美金结算订单数
                        }
                        else
                        {
                            WeekRMB += item.PurchaseRMB;//周总人民币
                        }
                    }
                    else
                    {
                        //现货                        
                    }
                }
                WeekExpense = WeekUSD * Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["BaseFreight"]);//周取货费用
            }
            #endregion
            //本周兑换记录
            #region
            IList<ExchangeResult> _exchangeInfo = YZ.GetDatabase(tttagKey).QueryForList<ExchangeResult>("Exchange.GetExchanges", param1);//本周兑换记录
            if (_exchangeInfo != null && _exchangeInfo.Count > 0)
            {
                foreach (var item in _exchangeInfo)
                {
                    totalUSD2 += item.Exchange * item.Amount;//总应支付金额
                    totalUSD3 += item.Amount;//总已兑换美金
                }
                WeekAvgExchange = totalUSD2 / totalUSD3;//周平均汇率
            }
            #endregion
            RestUSD = (totalUSD3) - (WeekUSD + WeekExpense);
            if (RestUSD.Value < 0)
            {
                param2["RestUSD"] = 0;//负数为剩余0
            }
            else
            {
                param2["RestUSD"] = RestUSD.Value;
            }
            param2["WeekPurchaseExchange"] = WeekAvgExchange;
            return param2;
        }
        #endregion

        #region  供应商数据过滤
        /// <summary>
        /// 中心供应商列表 2017-03-08
        /// </summary>
        /// <returns></returns>
        public string GetCenterSuppliers(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            try
            {
                string productName = "";
                int goodType = 0;
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定类别");
                }
                else
                {
                    goodType = hsParam.GetInt("GoodsType").Value;
                }
                string result = string.Empty;
                //1;裸钻2;统包3;成品4;彩宝5;翡翠6;素金 
                if (goodType == GoodsType.Diamond)
                {
                    productName = "diamond";
                }
                else if (goodType == GoodsType.Parcel)
                {
                    productName = "parcel";
                }
                else if (goodType == GoodsType.Ring)
                {
                    productName = "ring";
                }
                else if (goodType == GoodsType.Gem)
                {
                    productName = "gem";
                }
                else if (goodType == GoodsType.Emerald)
                {
                    productName = "emerald";
                }
                else if (goodType == GoodsType.PrimeGolds)
                {
                    productName = "primegolds";
                }
                else if (goodType == GoodsType.InlaySettings)
                {
                    productName = "inlaysettings";
                }
                else
                {
                    return CommonLog.MsgErrorInfo("未知的商品类别");
                }
                {
                    //从设置里取得已开的供应商
                    string whiteSupplier = MyHttpRequest.GetSupplierByCondition(tttagKey, productName);
                    WhiteSupplier whiteSupplierList = Json.Deserialize<WhiteSupplier>(whiteSupplier);
                    //从数据中心获取所有供应商
                    string allSupplier = MyHttpRequest.GetSupplierListFromDataCenter(tttagKey).Replace("prime-golds", "prime_golds").Replace("inlay-settings", "inlay_settings");
                    if (whiteSupplierList == null || whiteSupplierList.result == false)
                        return allSupplier;
                    SupplierRow allSupplierList = Json.Deserialize<SupplierRow>(allSupplier);
                    //只显示白名单 whiteSupplierList  allSupplierList 交集
                    var names = whiteSupplierList.msg.ToList().Select(p => p.name.ToUpper()).ToList();
                    if (!names.Contains(tttagKey))
                    {
                        names.Add(tttagKey);
                    }
                    //白名单
                    var resultSupplier = from all in allSupplierList.rows
                                         where names.Contains(all.supplier.ToUpper())
                                         select all;


                    string aa = JsonConvert.SerializeObject(resultSupplier).Replace("prime_golds", "prime-golds").Replace("inlay_settings", "inlay-settings");
                    string result1 = "{\"rows\": " + aa + "}";
                    return result1;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return "";
        }
        /// <summary>
        /// 单个远程供应商 12-27
        /// </summary>
        /// <param name="getSupplierParam"></param>
        /// <returns></returns>
        public string GetCenterSupplier(string getCenterSupplierParam)
        {
            logParam = getCenterSupplierParam;
            HashParam param = Json.Deserialize<HashParam>(getCenterSupplierParam);
            string tttagKey = CommonUrl.getURL(param, getCenterSupplierParam);
            //#msg 和"#msg" 
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数
                RequestInfo rif = new RequestInfo() { RequestJson = getCenterSupplierParam, RequestUrl = string.Format(GlobalConfig.TransmissionSuppliersUrl, param.GetString("supplierCode")) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //(Rapnet)
                if (responseJson.Contains("result\": false"))
                    return responseJson.Replace("false", "\"false\"").Replace("msg", "msginfo").Replace("result", "msgcode");
                else
                    return CommonLog.MsgSuccessInfo(responseJson);
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 得到单个供应商设置
        /// </summary>
        /// <returns></returns>
        public string GetSupplierSet(string getParcelParam)
        {
            logParam = getParcelParam;
            HashParam param = Json.Deserialize<HashParam>(getParcelParam);
            string tttagKey = CommonUrl.getURL(param, getParcelParam);
            //#msg 和"#msg" 
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数
                RequestInfo rif = new RequestInfo() { RequestJson = getParcelParam, RequestUrl = string.Format(GlobalConfig.TransmissionSupplierSetUrl, param.GetString("supplierCode")) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载单个供应商失败，程序错误");
            }
        }
        /// <summary>
        /// 得到多个供应商设置列表
        /// </summary>
        /// <returns></returns>
        public string GetSuppliersSet(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数
                RequestInfo rif = new RequestInfo() { RequestUrl = string.Format(GlobalConfig.TransmissionSuppliersSetUrl) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载失败，程序错误");
            }
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="tttagKey"></param>
        /// <param name="messeage"></param>
        private void SendMQMsg(string tttagKey, string messeage)
        {
            Msg msgS = new Msg();
            msgS.TagKey = tttagKey;
            msgS.Desc = messeage;
            ConmonMQMsgClass.send(msgS);
        }
        public int DelSupplier(string setSupplierParam)
        {
            logParam = setSupplierParam;
            string tttagKey = CommonUrl.getURL(null, setSupplierParam);
            var supplierAttach = JsonConvert.DeserializeObject<SupplierAttach>(setSupplierParam);
            var a = YZ.GetDatabase(tttagKey).Delete("Supplier.BatchDelete", supplierAttach);
            return a;
        }
        /// <summary>
        /// 加入或移除黑名单
        /// //Set供应商(单个)，supplierCode名字，category类别（stocks，inlays，parcels），state 状态( false, #不在黑名单中| true, #在黑名单中)
        /// </summary>
        /// <param name="modParcelParam"></param>
        /// <returns></returns>
        public string SetSupplier(string setSupplierParam)
        {
            logParam = setSupplierParam;
            HashParam setParam = JsonConvert.DeserializeObject<HashParam>(setSupplierParam);
            string tttagKey = CommonUrl.getURL(setParam, setSupplierParam);
            //#msg 和"#msg" 
            try
            {
                //params:stocks,parcels,inlays, ,setSupplierID,setSupplier bool 
                //stocks": false, #不在黑名单中
                //"parcels": true, #在黑名单中
                //"inlays": false,
                //参数可全空 
                //设置开前要做的事
                //1检查供应商对应的类别是否存在
                if (setParam.GetBool("state") && setParam.GetInt("SupplierType") > 0)
                {
                    SupplierInfo supplier = YZ.GetDatabase(tttagKey).QueryForObject<SupplierInfo>("Supplier.RegIsExist", setParam);
                    if (supplier == null)
                    {
                        supplier = new SupplierInfo()
                        {
                            SupplierCode = setParam.GetString("SupplierCode"),
                            SupplierName = setParam.GetString("supplierName"),
                            SupplierShortName = setParam.GetString("SupplierShortName"),
                            SupplierType = setParam.GetInt("SupplierType")
                        };
                        var a = YZ.GetDatabase(tttagKey).Add(supplier);
                        if (a == 0)
                        {
                            return CommonLog.MsgErrorInfo("本地添加供应商失败");
                        }
                    }
                }
                else if (setParam.GetInt("SupplierType") > 0)
                {
                    YZ.GetDatabase(tttagKey).Delete("Supplier.DeleteSupplier", setParam);
                }
                Dictionary<string, bool> dicts = new Dictionary<string, bool>(); //组装成新的数据中心的格式
                dicts.Add(setParam.GetString("category"), setParam.GetBool("state"));
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(dicts));
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = JsonConvert.SerializeObject(dicts), RequestUrl = string.Format(GlobalConfig.TransmissionSupplierWhiteSetUrl, setParam.GetString("SupplierCode")) };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT);
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 加入或移除白名单
        /// </summary>
        /// <param name="setSupplierParam"></param>
        /// <returns></returns>
        public string SetSupplierWhite(string setSupplierParam)
        {
            logParam = setSupplierParam;
            HashParam setParam = JsonConvert.DeserializeObject<HashParam>(setSupplierParam);
            string tttagKey = CommonUrl.getURL(setParam, setSupplierParam);
            //#msg 和"#msg" 
            //params:stocks,parcels,inlays, ,setSupplierID,setSupplier bool 
            //stocks": false, #不在白名单中
            //"parcels": true, #在白名单中
            //"inlays": false,
            //参数可全空
            Dictionary<string, bool> dicts = new Dictionary<string, bool>(); //组装成新的数据中心的格式
            dicts.Add(setParam.GetString("category"), setParam.GetBool("state"));
            try
            {
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(dicts));
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = JsonConvert.SerializeObject(dicts), RequestUrl = string.Format(GlobalConfig.TransmissionSupplierWhiteSetUrl, setParam.GetString("supplierCode")) };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT);
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// //Set供应商(多个)，blacklist,黑名单list， stocks钻石，parcels统包，inlays成品 ....，["abc", "def"]指（钻石）拉黑：abc，及def两家供应商
        /// </summary>
        /// <param name="modParcelParam"></param>
        /// <returns></returns>
        public string SetSuppliers(string setSupplierParam)
        {
            logParam = setSupplierParam;
            string tttagKey = CommonUrl.getURL(null, setSupplierParam);
            //#msg 和"#msg" 
            //提交格式
            //{
            //     "blacklist": {
            //         "stocks": ["abc", "def"],
            //         "parcels": ["def", "ghi"],
            //         "inlays": ["jkl", "mno"]
            //     }
            // }
            //参数可全空
            try
            {
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(setSupplierParam);
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = setSupplierParam, RequestUrl = string.Format(GlobalConfig.TransmissionSuppliersSetUrl) };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT);
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务成功");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("设置供应商单个失败，程序错误");
            }
        }
        #endregion
        #region  兑换记录Exchange
        /// <summary>
        /// 兑换列表 01-03
        /// </summary>
        /// <param name="getExchangesParam"></param>
        /// <returns></returns>
        public string GetExchanges(string getExchangesParam)
        {
            logParam = getExchangesParam;
            HashParam param = Json.Deserialize<HashParam>(getExchangesParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getExchangesParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                PageList<ExchangeResult> _exchanges = YZ.GetDatabase(tttagKey).QueryForList<ExchangeResult>("Exchange.GetExchanges", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));//ToInt32 9-6
                if (_exchanges != null && _exchanges.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_exchanges));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 最近的采购汇率
        /// </summary>
        /// <returns></returns>
        public string ComputePurchaseExchange(string getExchangeListParam)
        {
            logParam = getExchangeListParam;
            HashParam param = Json.Deserialize<HashParam>(getExchangeListParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getExchangeListParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                IList<ExchangeResult> _exchanges = YZ.GetDatabase(tttagKey).QueryForList<ExchangeResult>("Exchange.GetExchanges", param);
                if (_exchanges != null && _exchanges.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_exchanges));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 修改采购汇率 9-6
        /// </summary>
        /// <param name="arrivalOrdersParam"></param>
        /// <returns></returns>
        public string ExchangeOrders(string exchangeOrdersParam)
        {
            logParam = exchangeOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(exchangeOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, exchangeOrdersParam);
            //OrderIDs(必填) 、PurchaseExchangerate(必传)
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            try
            {
                int Successful = 0;//成功
                int Failed = 0;//失败
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                if (_orderIDs.Length > 0)
                {
                    OrderInfo _order = new OrderInfo();
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        try
                        {
                            _order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID（OrderID）
                            _order.PurchaseExchangerate = param.GetDecimal("PurchaseExchangerate",1);//采购汇率 9-6
                            using (ITransaction trans_exchangeOrders = YZ.GetTransaction(tttagKey))
                            {
                                int exchangeOrdersResult = trans_exchangeOrders.Edit(_order);
                                //单条成功后，就执行入库订单事务
                                if (exchangeOrdersResult > 0)
                                {
                                    try
                                    {
                                        trans_exchangeOrders.CommitTransaction(); //触发入库事务
                                        Successful++;//成功
                                    }
                                    catch (Exception)
                                    {
                                        trans_exchangeOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                else
                                {
                                    Failed++;//失败
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            return _msgInfo.Replace("#code", "false").Replace("#msg", "修改失败，程序错误").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject((Failed)));
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "修改成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject((Failed)));//不考虑OrderID不存在的情况
                }
                else
                {
                    return _msgInfo.Replace("#code", "false").Replace("#msg", "没选择任何订单").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject((Failed)));
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return _msgInfo.Replace("#code", "false").Replace("#msg", "修改失败，程序错误").Replace("#succ", JsonConvert.SerializeObject("0")).Replace("#fail", JsonConvert.SerializeObject("0"));
            }
        }
        #endregion
        #region 供应商相关
        /// <summary>
        /// 供应商联系方式 11-5
        /// </summary>
        /// <param name="contactParam"></param>
        /// <returns></returns>
        public string ContactSupplier(string contactParam)
        {
            logParam = contactParam;
            HashParam param = Json.Deserialize<HashParam>(contactParam);
            string tttagKey = CommonUrl.getURL(param, contactParam);
            //#msg 和"#msg"
            try
            {
                string SupplierCode = param.GetString("SupplierCode");
                if (SupplierCode != "")
                {
                    var requestUrl = GlobalConfig.BaseURL + string.Format("suppliers/{0}", SupplierCode);  //V1版本请求地址https://yunzuandc.com/api/v1/ 测试http://112.74.39.72:8200/api/v2/    正式http://api.checkgems.com/api/v2/
                    string guid = Guid.NewGuid().ToString();
                    int totalSeconds;
                    string signStr;
                    MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);
                    RequestInfo rif = new RequestInfo() { RequestJson = contactParam, RequestUrl = requestUrl };
                    var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //(Rapnet)
                    if (responseJson.Contains("Traceback"))
                    {
                        return CommonLog.MsgErrorInfo("接口故障");//401 500
                    }
                    else
                    {
                        return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(responseJson));
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("空白供应商，联系方式不存在");//401 500
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 所有供应商 9-6
        /// </summary>
        /// <param name="getSuppliersParam"></param>
        /// <returns></returns>
        public string GetSupplierList(string getSupplierListParam)
        {
            logParam = getSupplierListParam;
            string tttagKey = CommonUrl.getURL(null, getSupplierListParam);
            //#msg 和"#msg"
            try
            {
                IList<SupplierInfo> _suppliersInfo = YZ.GetDatabase(tttagKey).QueryForList<SupplierInfo>("Supplier.GetList", null);
                if (_suppliersInfo != null && _suppliersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_suppliersInfo));//_ordersInfo.Data 不含_ordersInfo.FooterData
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载供应商列表失败，程序错误");
            }
        }
        /// <summary>
        /// 添加供应商 -- 含事务
        /// </summary>
        /// <param name="addCustomerParam"></param>
        /// <returns></returns>
        public string AddSupplier(string addSupplierParam)
        {
            logParam = addSupplierParam;
            string tttagKey = CommonUrl.getURL(null, addSupplierParam);
            //UserPassword(必传)
            //templateJSON
            SupplierInfo param = Json.Deserialize<SupplierInfo>(addSupplierParam);
            param.CreateTime = DateTime.Now;//注册时间
            try
            {
                using (ITransaction trans_addSupplier = YZ.GetTransaction(tttagKey))
                {
                    int addSupplierResult = trans_addSupplier.Add(param);
                    if (addSupplierResult > 0)
                    {
                        try
                        {
                            trans_addSupplier.CommitTransaction();
                            HttpContext.Current.Cache.Remove("Cache:Suppliers");//2017-01-10 清除供应商调价缓存-重要!!!!
                            return CommonLog.MsgSuccessInfo("添加成功");
                        }
                        catch (Exception e)
                        {
                            trans_addSupplier.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("添加失败:");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("添加失败，程序错误");
            }
        }
        /// <summary>
        /// 修改供应商
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public string EditSupplier(string editSupplierParam)
        {
            logParam = editSupplierParam;
            string tttagKey = CommonUrl.getURL(null, editSupplierParam);
            //CustomerID（必传）
            //templateJSON
            SupplierInfo param = Json.Deserialize<SupplierInfo>(editSupplierParam);
            try
            {
                param.UpdateTime = DateTime.Now;
                using (ITransaction trans_editSupplier = YZ.GetTransaction(tttagKey))
                {
                    int editCustomerResult = trans_editSupplier.Edit(param);
                    if (editCustomerResult > 0)
                    {
                        try
                        {
                            trans_editSupplier.CommitTransaction();
                            HttpContext.Current.Cache.Remove("Cache:Suppliers");//2017-01-10 清除供应商调价缓存
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        catch (Exception e)
                        {
                            trans_editSupplier.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("修改失败:");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改失败，程序错误");
            }
        }
        /// <summary>
        /// 供应商列表------ 纯粹读数据 无需 事务
        /// </summary>
        /// <param name="getOrdersParam"></param>
        /// <returns></returns>
        public string GetSuppliers(string getSuppliersParam)
        {
            logParam = getSuppliersParam;
            HashParam param = Json.Deserialize<HashParam>(getSuppliersParam);//用PageParam是个坑 9-5
            string tttagKey = CommonUrl.getURL(param, getSuppliersParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                PageList<SupplierInfo> _suppliersInfo = YZ.GetDatabase(tttagKey).QueryForList<SupplierInfo>("Supplier.GetList", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));
                if (_suppliersInfo != null && _suppliersInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_suppliersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载供应商列表失败，程序错误");
            }
        }
        /// <summary>
        /// 单个供应商信息
        /// </summary>
        /// <param name="customerInfoParam"></param>
        /// <returns></returns>
        public string GetSupplierInfo(string supplierInfoParam)
        {
            logParam = supplierInfoParam;
            string tttagKey = CommonUrl.getURL(null, supplierInfoParam);
            //templateJSON
            SupplierInfo param = Json.Deserialize<SupplierInfo>(supplierInfoParam); //解析Android传过来的Json   //Deserialize 反序列化
            try
            {
                SupplierInfo supplier = YZ.GetDatabase(tttagKey).Get<SupplierInfo>(param.SupplierID);
                if (supplier != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(supplier));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取失败，请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }


        /// <summary>
        /// 供应商角色
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QuerySupplierRole(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            try
            {

                var result = YZ.GetDatabase(tttagKey).QueryForList<SupplierRole>("SupplierRole.GetRoles", null);
                if (result.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(result));
                }
                else
                    return CommonLog.MsgErrorInfo("查询供应商角色无记录");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("查询供应商角色，服务器内部错误");
                throw;
            }

        }
        /// <summary>
        /// 供应商添加简称是否存在
        /// </summary>
        /// <returns></returns>
        public string SupplierRegIsExist(string supplierRegIsExistParam)
        {
            logParam = supplierRegIsExistParam;
            HashParam param = Json.Deserialize<HashParam>(supplierRegIsExistParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, supplierRegIsExistParam);
            //判断简称是否已存在
            //templateJSON
            try
            {
                string _supplierCode = param.GetString("SupplierCode");//简称
                if (!string.IsNullOrEmpty(_supplierCode))
                {
                    SupplierInfo supplierResult = YZ.GetDatabase(tttagKey).QueryForObject<SupplierInfo>("Supplier.RegIsExist", param);
                    if (supplierResult != null)
                    {
                        return CommonLog.MsgErrorInfo("已存在");
                    }
                    else
                    {
                        return CommonLog.MsgSuccessInfo("可以注册");
                    }
                }
                return CommonLog.MsgErrorInfo("请输入简称");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("服务器错误");
            }
        }
        #endregion
        #region 网站对应的联系方式链接（qq,skype）
        //查询
        public string GetLink(string param)
        {
            return AllPublic.GetLink(param);
        }
        //修改网站对应的联系方式链接（qq,skype）
        public string UpdateLink(string param)
        {
            return AllPublic.UpdateLink(param);
        }
        #endregion
        #region Rapnet报价列表
        public string GetRapnetByParam(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            var msg = "{\"message\":\"#msg\",\"result\":\"#result\"}";
            try
            {
                RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                OrderInfo _order = JsonConvert.DeserializeObject<OrderInfo>(param);
                return msg.Replace("#msg", rap.GetPrice(_order).ToString()).Replace("#result", "true");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return msg.Replace("#msg", "获取失败").Replace("#result", "false");
            }
        }
        /// <summary>
        /// 报价表列表
        /// </summary>
        /// <returns></returns>
        public string GetRapnetList()
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                string priceFileName = AppDomain.CurrentDomain.BaseDirectory + "App_data\\diamond_all_price.xml";
                xmldoc.Load(priceFileName);
                Dictionary<string, string> priceList = new Dictionary<string, string>();
                XmlNodeList xnlPrice = xmldoc.SelectNodes("/items/item");
                StringBuilder builderPrice = new StringBuilder();
                foreach (XmlNode item in xnlPrice)
                {
                    builderPrice.Append("\"" + item.Attributes["key"].InnerText.Replace("round_", "R").Replace("other_", "P") + "\":" + item.Attributes["value"].InnerText + ",");
                }
                string rapnetList = "{" + builderPrice.ToString().TrimEnd(',') + "}";//报价表json
                if (xnlPrice.Count > 0)
                {
                    //报价表
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(rapnetList));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("本地报价表内容错误，正确示例<item key='' value=''/>");//报价表
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("获取报价列表失败:");
            }
        }
        #endregion
        #region 出货单
        /// <summary>
        /// 查询出货单
        /// </summary>
        /// <param name="CancelGemOrdersParam"></param>
        /// <returns></returns>
        public string GetAllShipNo(string shipOrdersParam)
        {
            logParam = shipOrdersParam;
            HashParam param = JsonConvert.DeserializeObject<HashParam>(shipOrdersParam);
            string tttagKey = CommonUrl.getURL(param, shipOrdersParam);
            PageList<ShippingList> orderInfoList = YZ.GetDatabase(tttagKey).QueryForList<ShippingList>("Order.GetShipNoByParam", param, Convert.ToInt32(param["PageSize"]), Convert.ToInt32(param["PageIndex"]));
            if (orderInfoList != null && orderInfoList.Data.Count > 0)
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(orderInfoList));
            }
            else
            {
                return CommonLog.MsgErrorInfo("没有任何订单");
            }
        }
        /// <summary>
        /// 查询订单通过出货单号
        /// </summary>
        /// <param name="CancelGemOrdersParam"></param>
        /// <returns></returns>
        public string GetAllOrderByShipNo(string shipOrdersParam)
        {
            logParam = shipOrdersParam;
            HashParam param = JsonConvert.DeserializeObject<HashParam>(shipOrdersParam);
            string tttagKey = CommonUrl.getURL(param, shipOrdersParam);
            IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderByShipNo", param);//OrderIDs
            if (OrderList != null && OrderList.Count > 0)
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(OrderList));
            }
            else
            {
                return CommonLog.MsgErrorInfo("没有任何订单");
            }
        }
        /// <summary>
        /// 删除出货单里面的订单
        /// </summary>
        /// <param name="CancelGemOrdersParam"></param>
        /// <returns></returns>
        public string DeleteOrderInShipNoByOrderIdsOrShipNo(string shipOrdersParam)
        {
            logParam = shipOrdersParam;
            string tttagKey = CommonUrl.getURL(null, shipOrdersParam);
            OrderInfo param = JsonConvert.DeserializeObject<OrderInfo>(shipOrdersParam);
            var i = YZ.GetDatabase(tttagKey).Update("Order.DeleteOrderInShipNoByOrderIdsOrShipNo", param);//OrderIDs｜ShipNo
            if (i > 0)
            {
                return CommonLog.MsgSuccessInfo("删除成功!");//返回Jason数据                    
            }
            else
            {
                return CommonLog.MsgErrorInfo("删除失败!");
            }
        }
        public string GetOrderShipNoCount(string param)
        {
            var logParam = param;
            HashParam hsParam = Json.Deserialize<HashParam>(param);
            string tttagKey = CommonUrl.getURL(hsParam, param, "统计出货单各状态数量");
            try
            {
                OrderShipNoCount info = YZ.GetDatabase(tttagKey).QueryForObject<OrderShipNoCount>("Order.SelectShipNoCount", "");
                if (info != null)
                {
                    return JsonConvert.SerializeObject(info);
                }
                else
                    return CommonLog.MsgErrorInfo("获取信息失败，请重试");
            }
            catch (Exception ex)
            {
                return CommonLog.MsgErrorInfo("修改失败");
            }
        }
        #endregion 出货单end
        #region 职能角色
        public string GetJobTitleInfo(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            IList<JobTitleByRole> jTitles = YZ.GetDatabase(tttagKey).QueryForList<JobTitleByRole>("JobTitle.GetJobTitle", null);
            if (jTitles.Count > 0)
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(jTitles));
            }
            else
            {
                return CommonLog.MsgErrorInfo("没有数据!");
            }
        }
        /// <summary>
        ///  修改 职能
        /// </summary>
        /// <param name="batchUpdateDiaParam"></param>
        /// <returns></returns>
        public string UpdateJobTitle(string updateParam)
        {
            logParam = updateParam;
            string tttagKey = CommonUrl.getURL(null, updateParam);
            JobTitleByRole jobTitleRole = JsonConvert.DeserializeObject<JobTitleByRole>(updateParam);
            try
            {
                using (ITransaction trans = YZ.GetTransaction(tttagKey))
                {
                    int result = trans.Edit(jobTitleRole);
                    if (result > 0)
                    {
                        trans.CommitTransaction();
                        return CommonLog.MsgSuccessInfo("更新成功");
                    }
                    else
                    {
                        trans.RollBackTransaction();
                        return CommonLog.MsgErrorInfo("更新失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        ///  新增 职能
        /// </summary>
        /// <param name="batchUpdateDiaParam"></param>
        /// <returns></returns>
        public string AddJobTitle(string addParam)
        {
            logParam = addParam;
            string tttagKey = CommonUrl.getURL(null, addParam);
            JobTitleByRole jobTitleRole = JsonConvert.DeserializeObject<JobTitleByRole>(addParam);
            try
            {
                using (ITransaction trans = YZ.GetTransaction(tttagKey))
                {
                    int result = trans.Add(jobTitleRole);
                    if (result > 0)
                    {
                        trans.CommitTransaction();
                        return CommonLog.MsgSuccessInfo("增加成功");
                    }
                    else
                    {
                        trans.RollBackTransaction();
                        return CommonLog.MsgErrorInfo("增加失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #endregion
        #region  菜单列表
        public string GetMenuList(string menuParam)
        {
            logParam = menuParam;
            HashParam param = Json.Deserialize<HashParam>(menuParam);
            string tttagKey = CommonUrl.getURL(param, menuParam);
            IList<MenuList> jTitles = YZ.GetDatabase(tttagKey).QueryForList<MenuList>("MenuList.GetMenuList", param);
            if (jTitles.Count > 0)
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(jTitles));
            }
            else
            {
                return CommonLog.MsgErrorInfo("没有数据!");
            }
        }
        #endregion

        #region 其它订单相关
        //录入
        /// <summary>
        /// 添加大类
        /// </summary>
        /// <param name="addOrderParam"></param>
        /// <returns></returns>
        public string AddOtherBigType(string addOrderParam)
        {
            //HashParam param = JsonConvert.DeserializeObject<HashParam>(addOrderParam);
            //一级ParentID为0
            return AddOtherType(addOrderParam);
        }
        /// <summary>
        /// 添加小类
        /// </summary>
        /// <param name="addOrderParam"></param>
        /// <returns></returns>
        public string AddOtherSmallType(string addOrderParam)
        {
            return AddOtherType(addOrderParam);
        }
        public string AddOtherType(string createOrderParam)
        {
            logParam = createOrderParam;
            string tttagKey = CommonUrl.getURL(null, createOrderParam);
            try
            {
                OtherType other = JsonConvert.DeserializeObject<OtherType>(createOrderParam);
                if (other.TypeName != "")
                {//查询有无此类型，如无则添加 //待添加 
                    var addOrderResult = YZ.GetDatabase(tttagKey).Add(other);
                    if (addOrderResult > 0)
                    {
                        return CommonLog.MsgSuccessInfo("生成类型成功");
                    }
                    else
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("生成类型失败");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("生成类型失败,类型名不能为空");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        public string AddUnitName(string createParam)
        {
            try
            {
                logParam = createParam;
                string tttagKey = CommonUrl.getURL(null, createParam);
                Unit other = JsonConvert.DeserializeObject<Unit>(createParam);
                var addResult = YZ.GetDatabase(tttagKey).Add(other);
                if (addResult > 0)
                {
                    return CommonLog.MsgSuccessInfo("单位添加成功");
                }
                else
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("单位添加失败");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        public string GetUnit(string getParam)
        {
            try
            {
                logParam = getParam;
                HashParam param = JsonConvert.DeserializeObject<HashParam>(getParam);
                string tttagKey = CommonUrl.getURL(param, getParam);
                var getResult = YZ.GetDatabase(tttagKey).QueryForList<Unit>("Unit.GetUnit", param);
                if (getResult.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(getResult));
                }
                else
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("获取类型失败");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 查询大类
        /// </summary>
        /// <param name="addOrderParam"></param>
        /// <returns></returns>
        public string GetOtherBigType(string param)
        {
            //一级ParentID为0
            //return GetOtherType(JsonConvert.SerializeObject((new { ParentID = 0 })));
            return GetOtherType(param);
        }
        /// <summary>
        /// 查询小类
        /// </summary>
        /// <param name="addOrderParam"></param>
        /// <returns></returns>
        public string GetOtherSmallType(string getOrderParam)
        {
            return GetOtherType(getOrderParam);
        }
        public string GetOtherType(string getOrderParam)
        {

            logParam = getOrderParam;
            HashParam param = JsonConvert.DeserializeObject<HashParam>(getOrderParam);
            string tttagKey = CommonUrl.getURL(param, getOrderParam);
            try
            {
                var getOrderResult = YZ.GetDatabase(tttagKey).QueryForList<OtherType>("Other_Type.GetOtherType", param);
                if (getOrderResult.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(getOrderResult));
                }
                else
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("获取类型失败");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }


        //删除作废订单
        public string OtherDelOrders(string delOrdersParam)
        {
            logParam = delOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            delOrdersResult = trans_delOrders.Delete("OtherOrder.DelOrders", _orderIDs[i]);//删除结果
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }



        #endregion
        #region 翡翠相关
        /// <summary>
        /// //翡翠列表
        /// </summary>
        /// <param name="getEmeraldsParam"></param>
        /// <returns></returns>
        public string GetEmeralds(string getEmeraldsParam)
        {
            string tttagKey = CommonUrl.getURL(null, getEmeraldsParam);
            return GetProduct<EmeraldInfoResult>(tttagKey, getEmeraldsParam, GlobalConfig.TransmissionEmeraldSearchUrl, GoodsType.Emerald);
        }
        /// <summary>
        /// 单个翡翠查询
        /// </summary>
        /// <param name="getEmeraldParam"></param>
        /// <returns></returns>
        public string GetEmerald(string getEmeraldParam)
        {
            logParam = getEmeraldParam;
            HashParam param = Json.Deserialize<HashParam>(getEmeraldParam);
            string tttagKey = CommonUrl.getURL(param, getEmeraldParam);
            string responseJson = CRetails.AllProduct(tttagKey, getEmeraldParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, param.GetInt("ID")), "get");
            if (responseJson.Contains(".py") || responseJson.Contains("程序错误"))
            {
                return responseJson.Replace("false", "\"false\"").Replace("#msg", "远程服务错误");
            }
            else
            {
                Emerald product = CalProductPrice<Emerald>(param, responseJson, GoodsType.Emerald, tttagKey);
                responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));

            }
            return responseJson;
        }
        //修改翡翠
        public string ModEmeralds(string modEmeraldsParam)
        {
            logParam = modEmeraldsParam;
            string tttagKey = CommonUrl.getURL(null, modEmeraldsParam);
            Emerald emerald = Json.Deserialize<Emerald>(modEmeraldsParam);
            return CRetails.AllProduct(tttagKey, modEmeraldsParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, emerald.ID), "put");
        }
        //添加翡翠
        public string AddEmeralds(string modEmeraldsParam)
        {
            logParam = modEmeraldsParam;
            string tttagKey = CommonUrl.getURL(null, modEmeraldsParam);
            Emerald emerald = Json.Deserialize<Emerald>(modEmeraldsParam);
            return CRetails.AllProduct(tttagKey, modEmeraldsParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, ""), "post");
        }
        //删除翡翠
        public string DeleteEmeralds(string delEmeraldsParam)
        {
            logParam = delEmeraldsParam;
            string tttagKey = CommonUrl.getURL(null, delEmeraldsParam);
            Emerald emerald = Json.Deserialize<Emerald>(delEmeraldsParam);
            return CRetails.AllProduct(tttagKey, delEmeraldsParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, emerald.ID), "delete");
        }

        /// <summary>
        /// 移除购物车
        /// </summary>
        /// <param name="ringCartId"></param>
        /// <returns></returns>
        public string RemoveEmeraldsCart(string removeFromCartParam)
        {
            return DelAllCartByCustomerIdAndProductIds(removeFromCartParam, "EmeraldIDs", "Emerald_Cart.DeleteByEmeraldIDs");
        }

        #endregion 翡翠结束



        #region 全局日志
        public static SearchParamLog log = new SearchParamLog();
        /// <summary>
        /// 得到当前方法并记录日志
        /// </summary>
        /// <param name="ex"></param>
        private void GetMethodInfoAndWriteLogs(Exception ex = null, string logParam = "", string msg = "")
        {
            var type = typeof(Retail);
            try
            {
                StackTrace st = new StackTrace(true);
                MethodBase mb = st.GetFrame(1).GetMethod();
                var line = "";
                var errInfo = "";
                var paramName0 = "";//记录第一个参数名
                if (ex != null)
                {
                    if (ex.StackTrace.IndexOf("行号") > -1) //有些错误信息没有行号，导致什么信息都没有记录
                    {
                        line = ex.StackTrace.Substring(ex.StackTrace.IndexOf("行号"), ex.StackTrace.Length - ex.StackTrace.IndexOf("行号")); //行号
                    }
                    errInfo = ex.Message;
                }

                //取得父参数名
                if (mb.GetParameters().Count() > 0)
                {
                    paramName0 = mb.GetParameters()[0].Name;
                }
                var logTemplate = string.Format(_logTemplate, mb.Name, paramName0, line, logParam);
                if (msg != "")
                {
                    Logger.Info(type, logTemplate + "-记录信息：" + msg);
                }
                else
                    Logger.Error(type, logTemplate + "-错误信息：" + errInfo);
            }
            catch (Exception e)
            {
                Logger.Error(type, logParam + "-写日志出错信息：" + e.Message + ",e.StackTrace:" + e.StackTrace);
            }
        }
        #endregion 日志
        #region 客户联系方式
        //查询
        public string GetReceivingAddress(string param)
        {
            logParam = param;
            HashParam addParam = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(addParam, param);

            IList<ReceivingAddress> address = YZ.GetDatabase(tttagKey).QueryForList<ReceivingAddress>("ReceivingAddress.GetAddress", addParam);
            if (address.Count == 0)
            {
                return CommonLog.MsgErrorInfo("地址列表为空");
            }
            else
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(address));
            }
        }
        //客户联系方式
        public string EditReceivingAddress(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                ReceivingAddress address = JsonConvert.DeserializeObject<ReceivingAddress>(param);
                if (address != null)
                    return AddOrUpdateAndSetUniqueAddress(tttagKey, ref b, "edit", address);
                else
                    return CommonLog.MsgInfo(b, b ? "编辑成功" : "编辑失败");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgInfo(b, "编辑失败");
            }
        }
        //客户联系方式
        public string AddReceivingAddress(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                ReceivingAddress address = JsonConvert.DeserializeObject<ReceivingAddress>(param);
                CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(address.CustomerID);
                if (address != null && customer != null)
                    return AddOrUpdateAndSetUniqueAddress(tttagKey, ref b, "add", address);
                else
                    return CommonLog.MsgInfo(b, "增加失败，没有此客户");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("增加失败" + ex.Message);
            }
        }
        private static string AddOrUpdateAndSetUniqueAddress(string tttagKey, ref bool b, string optionType, ReceivingAddress address)
        {
            //开始事务
            using (ITransaction trans = YZ.GetTransaction(tttagKey))
            {
                string message;
                if (optionType == "add")
                {
                    message = "新增";
                    b = trans.Add(address) > 0;
                }
                else
                {
                    message = "编辑";
                    b = trans.Edit(address) > 0;
                }
                if (b)
                {
                    //当前为默认，其它得处理成非默认值
                    if (address.IsDefault.Value)
                    {
                        int count = 0;
                        IList<ReceivingAddress> addresss = YZ.GetDatabase(tttagKey).QueryForList<ReceivingAddress>("ReceivingAddress.GetAddress", new ReceivingAddress() { CustomerID = address.CustomerID, IsDefault = address.IsDefault });
                        foreach (var item in addresss)
                        {
                            if (item.ID == address.ID)
                            {
                                count++; //count == addresss.Count 这里需要
                                break;
                            }
                            item.IsDefault = !item.IsDefault;//设置为非默认
                            //多条默认更新为非默认
                            count += trans.Edit(item);
                        }
                        //没有其它默认或多条记录全部更新
                        if (count == addresss.Count)
                            trans.CommitTransaction();
                        //有多条默认记录且更新失败了
                        else
                            trans.RollBackTransaction();
                    }
                    else
                        trans.CommitTransaction();
                }
                else
                    trans.RollBackTransaction();
                var a = trans.Get<ReceivingAddress>(address);
                return string.Format(CommonLog.msgInfoAddReturnIdJson, b.ToString().ToLower(), b == true ? message + "成功" : message + "失败", a.ID);
            }
        }
        //删除地址
        public string DeleteReceivingAddress(string param)
        {
            logParam = param;
            HashParam addParam = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(addParam, param);
            bool b = false;
            try
            {
                b = YZ.GetDatabase(tttagKey).Delete("ReceivingAddress.delAddress", addParam) > 0;
                return CommonLog.MsgInfo(b, b ? "删除成功" : "删除失败");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgInfo(b, "删除失败");
            }
        }
        #endregion
        #region 素金
        /// <summary>
        /// 新增素金
        /// </summary>
        /// <param name="PrimeGoldsParam"></param>
        /// <returns></returns>
        public string AddPrimeGolds(string PrimeGoldsParam)
        {
            logParam = PrimeGoldsParam;
            string tttagKey = CommonUrl.getURL(null, PrimeGoldsParam);
            return CRetails.AllProduct(tttagKey, PrimeGoldsParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, ""), "post");
        }
        /// <summary>
        /// 删除素金
        /// </summary>
        /// <param name="PrimeGoldsParam"></param>
        /// <returns></returns>
        public string DeletePrimeGolds(string PrimeGoldsParam)
        {
            logParam = PrimeGoldsParam;
            string tttagKey = CommonUrl.getURL(null, PrimeGoldsParam);
            PrimeGolds primeGolds = Json.Deserialize<PrimeGolds>(PrimeGoldsParam);
            return CRetails.AllProduct(tttagKey, PrimeGoldsParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, primeGolds.ID), "delete");
        }
        /// <summary>
        /// 查询素金
        /// </summary>
        /// <param name="PrimeGoldsParam"></param>
        /// <returns></returns>
        public string GetPrimeGold(string PrimeGoldParam)
        {
            logParam = PrimeGoldParam;
            HashParam param = Json.Deserialize<HashParam>(PrimeGoldParam);
            string tttagKey = CommonUrl.getURL(param, PrimeGoldParam);
            string responseJson = CRetails.AllProduct(tttagKey, PrimeGoldParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, param.GetInt("ID")), "get");
            Logger.Info(this.GetType(), "gemJson:" + responseJson);
            if (responseJson.Contains(".py") || responseJson.Contains("程序错误"))
            {
                responseJson = responseJson.Replace("false", "\"false\"").Replace("#msg", "远程服务错误");
            }
            else
            {
                try
                {
                    PrimeGolds product = CalProductPrice<PrimeGolds>(param, responseJson, GoodsType.PrimeGolds, tttagKey);
                    responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));

                }
                catch (Exception ex)
                {
                    responseJson = responseJson.Replace("false", "\"false\"").Replace("#msg", "远程服务错误");
                    GetMethodInfoAndWriteLogs(ex);
                }

            }
            return responseJson;

        }
        /// <summary>
        /// 更新素金
        /// </summary>
        /// <param name="PrimeGoldsParam"></param>
        /// <returns></returns>
        public string ModPrimeGolds(string PrimeGoldsParam)
        {
            string tttagKey = CommonUrl.getURL(null, PrimeGoldsParam);
            PrimeGolds primeGolds = Json.Deserialize<PrimeGolds>(PrimeGoldsParam);
            return CRetails.AllProduct(tttagKey, PrimeGoldsParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, primeGolds.ID), "put");
        }
        /// <summary>
        /// 素金
        /// </summary>
        /// <param name="getPrimeGoldsParam"></param>
        /// <returns></returns>
        public string GetPrimeGoldsFilters(string getPrimeGoldsParam)
        {
            string tttagKey = CommonUrl.getURL(null, getPrimeGoldsParam);
            return GetProduct<PrimeGoldsInfoResult>(tttagKey, getPrimeGoldsParam, GlobalConfig.TransmissionPrimeGoldsSearchUrl, GoodsType.PrimeGolds);
        }





        /// <summary>
        /// 删除客户与产品ids对应的所有购物车数据
        /// </summary>
        /// <param name="removeFromCartParam"></param>
        /// <param name="productIds"></param>
        /// <param name="productSql"></param>
        /// <returns></returns>
        private string DelAllCartByCustomerIdAndProductIds(string removeFromCartParam, string productIds, string productSql)
        {
            logParam = removeFromCartParam;
            Hashtable _param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(removeFromCartParam));
            string tttagKey = CommonUrl.getURL(null, removeFromCartParam);
            GetMethodInfoAndWriteLogs(null, "DelAllCartByCustomerIdAndProductIds:" + logParam);
            try
            {
                //一定要传产品id，因为sql是通用的，因为可以只通过客户删除所有产品
                if (_param.ContainsKey(productIds))
                {
                    int removeFromCartResult = YZ.GetDatabase(tttagKey).Delete(productSql, _param);//RingID
                    if (removeFromCartResult > 0)
                    {
                        return CommonLog.MsgSuccessInfo("移除成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("移除失败，数据不存在");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("移除失败，没有选中任何产品");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }



        /// <summary>
        /// 删除作废订单
        /// </summary>
        /// <param name="delOrdersParam"></param>
        /// <returns></returns>
        public string PrimeGoldsDelOrders(string delOrdersParam)
        {
            logParam = delOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(delOrdersParam);
            string tttagKey = CommonUrl.getURL(param, delOrdersParam);
            //OrderIDs
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}";
            int Failed = 0;//失败条目
            int Successful = 0;//成功条目
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55   订单IDs
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        using (ITransaction trans_delOrders = YZ.GetTransaction(tttagKey))
                        {
                            int delOrdersResult = 0;
                            delOrdersResult = trans_delOrders.Delete("PrimeGoldOrder.DelOrders", _orderIDs[i]);//删除结果
                            if (delOrdersResult > 0)
                            {
                                try
                                {
                                    //删除订单成功
                                    try
                                    {
                                        trans_delOrders.CommitTransaction(); //触发入库事务
                                        Successful++;
                                    }
                                    catch (Exception)
                                    {
                                        trans_delOrders.RollBackTransaction();//回滚事务
                                    }
                                }
                                catch (Exception)
                                {
                                    trans_delOrders.RollBackTransaction();//回滚事务
                                }
                            }
                            else
                            {
                                //删除失败
                                Failed++;
                            }
                        }
                    }
                    return _msgInfo.Replace("#code", "true").Replace("#msg", "删除成功").Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("删除失败，程序错误");
            }
        }



        #endregion 素金


        #region# 客户相关
        /// <summary>
        /// 客户登录（公司客户）
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string CustomerLogin(string customerLoginParam)
        {
            logParam = customerLoginParam;
            HashParam param = Json.Deserialize<HashParam>(customerLoginParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, customerLoginParam,"客户登录");
            GetMethodInfoAndWriteLogs(null, logParam);
            // customerLoginParam 为 string name, string pwd
            try
            {
                string _name = param.GetString("Name");//帐号
                string _pwd = param.GetString("Pwd");//密码
                //登录参数非空判断
                if (string.IsNullOrEmpty(_name) || string.IsNullOrEmpty(_pwd))
                {
                    return CommonLog.MsgErrorInfo("客户登录失败:帐号或密码为空");
                }
                //客户表Customer
                CustomerInfo _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.Login", _name);//通过用户名UserName
                if (_customer != null)
                {
                    if (_customer.UserPassword.Equals(Yunzuan.Foundation.Safe.EncryptHelper.MD5(_pwd)))
                    {
                        //客户帐号状态SysStatus（-1 已删除 0 已禁用 2 审核中 1正常）

                        try
                        {
                            //更新客户的登录次数LoginCount 、上次活跃时间LastActiveTime 和 活跃IP
                            _customer.ActiveIP = param.GetString("ActiveIP");
                            int customerLoginResult = YZ.GetDatabase(tttagKey).Edit(_customer);
                            if (customerLoginResult > 0)
                            { 
                                UserLoginLog userloginlog = new UserLoginLog();
                                userloginlog.HttpURL = param.GetString("HttpURL");
                                userloginlog.tttagKey = tttagKey;
                                userloginlog.UserType = "1";//团队1，客户2
                                userloginlog.LoginUserID = _customer.CustomerID.ToString();
                                userloginlog.UserName = _customer.UserName;
                                userloginlog.Pwd = _pwd;
                                userloginlog.ActiveIP = param.GetString("ActiveIP");
                                userloginlog.OprationDesc = "客户登陆";
                                userloginlog.CreateDate = DateTime.Now;
                                string strP = JsonConvert.SerializeObject(userloginlog);
                                ConmonMQMsgClass.send("登陆" + strP);
                                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_customer));  
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("客户登录失败:数据库更新操作错误，请重试");
                            }
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            return CommonLog.MsgErrorInfo("客户登录失败，程序错误");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("客户登录失败:密码错误");
                    }
                }
                return CommonLog.MsgErrorInfo("客户登录失败:帐号不存在");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("客户登录失败，程序错误");
            }
        }
        #endregion#


        #region 订单重写 现零售用
        /// <summary>
        /// 提交订单(new) 
        /// </summary>
        /// <param name="submmitOrderParam"></param>
        /// <returns></returns>
        public string SubmitOrders(string submmitOrderParam, string isOpenInterface)
        {
            logParam = submmitOrderParam;
            //二级直接用YDT_BZ__PF(tttagKey) ,一级用YDT+SecondSN (supplierKey+secondSn)
            string tttagKey = CommonUrl.getURL(null, submmitOrderParam,"提交订单"); 

            //if (submmitOrderParam.Contains("openId"))
            //{
            //    //零售小程序没有customerid只有openId
            //    HashParam _param = JsonConvert.DeserializeObject<HashParam>(submmitOrderParam);
            //    _param.Add("CustomerID", GetCustomerIdByOpenid(_param.GetString("openId", ""), tttagKey));
            //    _param.Remove("openId");
            //    submmitOrderParam = JsonConvert.SerializeObject(_param);
            //}
            //{"CustomerID":"3","OnShelves":1,"InventoryList":[{"InventoryIDs":["10499679"],"GoodsTypeID":1},{"InventoryIDs":["65594"],"GoodsTypeID":3}]}
            InventoryParam param = Json.Deserialize<InventoryParam>(submmitOrderParam);
            string result = string.Empty;
            int succ = 0;
            int fail = 0;
            int fail1 = 0;
            if (param.InventoryList.Count > 0)
            {
                InventoryParamResult resultParam;
                for (int i = 0; i < param.InventoryList.Count; i++)
                {
                    resultParam = new InventoryParamResult();
                    resultParam.CustomerID = param.CustomerID;
                    resultParam.UserID = param.UserID;
                    resultParam.Remarks = param.Remarks;
                    resultParam.OnShelves = param.OnShelves;
                    resultParam.GoodsTypeID = param.InventoryList[i].GoodsTypeID;
                    resultParam.InventoryIDs = param.InventoryList[i].InventoryIDs;
                    resultParam.AddressID = param.AddressID;
                    resultParam.ParentKey = param.ParentKey;
                    resultParam.Mark = param.Mark; 
                    resultParam.ErJiMark = param.ErJiMark;//二级特有标识
                    resultParam.PublicParentUrl = param.PublicParentUrl;

                    string OrderParam = JsonConvert.SerializeObject(resultParam); //{"CustomerID":1,"OnShelves":1,"GoodsTypeID":1,"InventoryID":1,"InventoryCount":1}
                    int GoodTypeId = param.InventoryList[i].GoodsTypeID;
                    if (GoodTypeId == GoodsType.Diamond)
                    {
                        result = AddProductsOrder<InventoryInfoResult>(tttagKey, OrderParam, GoodsType.Diamond);
                    }
                    else if (GoodTypeId == GoodsType.Parcel)
                    {
                        result = AddProductsOrder<Parcels>(tttagKey, OrderParam, GoodsType.Parcel);
                    }
                    else if (GoodTypeId == GoodsType.Ring)
                    {
                        result = AddProductsOrder<Ring>(tttagKey, OrderParam, GoodsType.Ring);
                    }
                    else if (GoodTypeId == GoodsType.Gem)
                    {
                        result = AddProductsOrder<Gem>(tttagKey, OrderParam, GoodsType.Gem);
                    }
                    else if (GoodTypeId == GoodsType.Emerald)
                    {
                        result = AddProductsOrder<Emerald>(tttagKey, OrderParam, GoodsType.Emerald);
                    }
                    else if (GoodTypeId == GoodsType.PrimeGolds)
                    {
                        result = AddProductsOrder<PrimeGolds>(tttagKey, OrderParam, GoodsType.PrimeGolds);
                    }
                    else if (GoodTypeId == GoodsType.InlaySettings)
                    {
                        result = AddProductsOrder<InlaySettings>(tttagKey, OrderParam, GoodsType.InlaySettings);
                    }
                    if (isOpenInterface == "open_Interface" || isOpenInterface == "yiji_Api"|| resultParam.Mark=="lingshou")
                    {
                        return result;
                    }
                    var ResultParam = JsonConvert.DeserializeObject<ReturnOrderResult>(result);
                    succ += ResultParam.msginfo.Successful;
                    fail += ResultParam.msginfo.Failed;
                    fail1 += ResultParam.msginfo.Failed1;
                }
            }
            if (succ == 0 && fail == 0 && fail1 == 0)
                return CommonLog.MsgSuccessInfo("提交失败");
            return CommonLog.MsgSuccessInfo("提交订单成功" + succ + ",失败" + fail + ",被抢购" + fail1);
        }
        
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <param name="createOrderByCartParam"></param>
        /// <returns></returns>
        public string AddProductsOrder<T>(string tttagKey, string createOrderByCartParam, int systemType)
        {
            createOrderByCartParam = createOrderByCartParam.Replace("InventoryIDs", "ProductIDs").Replace("GemIDs", "ProductIDs").Replace("EmeraldIDs", "ProductIDs").Replace("ParcelIDs", "ProductIDs").Replace("RingIDs", "ProductIDs");//兼容处理，不用前端改参数

            var failCount = 0;
            var successCount = 0;
            var failCount1 = 0;
            var successCount1 = 0;

            StringBuilder tempSns = new StringBuilder();
            int goodsType = 0;
            Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(createOrderByCartParam), false);
            var token = param.ContainsKey("ParentKey") ? param["ParentKey"].ToString() : ""; 
            List<int> listScuccess = new List<int>();
            try
            {
                CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(int.Parse(param["CustomerID"].ToString()));//CustomerID必传
                if (customer != null)
                {
                    string filterUrl = GoodsType.GetGoodsFilters(systemType, ref goodsType);
                    SysSettingInfo setting = GetSystemSetting(systemType, goodsType, tttagKey);
                    decimal disc = 1; //全局折扣
                    //if (setting.GlobalFancyDiscountReturn.HasValue)
                    //{
                    //    disc= setting.GlobalFancyDiscountReturn.Value;
                    //}    
                    if (disc == 0) disc = 1;
                    //先将字符转字符数组，然后将字符数组转整形数组
                    #region
                    int[] _productIDs = (int[])param["ProductIDs"]; //param["ProductIDs"].ToString().TrimEnd(',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
                    List<int> listId = new List<int>();
                    #endregion
                    //无缓存 实时查询
                    #region 查货
                    var productIdsStr = CRetails.GetIdsStrParamByIds(_productIDs); //加入 useDict：true等元素
                     
                    string responseJson = string.Empty;
                    if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")//Mark是子级特有的标记
                    {
                        HashParam _param = new HashParam();
                        _param["useDict"] = true;
                        _param["CustomerID"] = param["CustomerID"];
                        _param["ID"] = _productIDs;
                        _param["GoodsType"] = goodsType;
                        _param["TagKey"] = tttagKey;
                        _param["ParentKey"] = token;
                        _param["ErJiMark"] = param["ErJiMark"];
                        if (param["ErJiMark"].ToString() == "2LSto1LS")//数据来源 2级零售版本，它的数据来源是一级零售
                        {
                            _param["PublicParentUrl"] = param["PublicParentUrl"];
 
                            _param.Remove("CustomerID");
 
                        }
                        else if (param["ErJiMark"].ToString() == "2LSto1PF")
                        {
                            _param.Remove("CustomerID");
                            //一级去下单
                        } 

                        productIdsStr = JsonConvert.SerializeObject(_param);
                        if (goodsType == GoodsType.Diamond)
                        {
                            responseJson = GetInventoryInfos(productIdsStr).Replace("TotalCount", "records").Replace("Data", "rows")
                                .Replace("SourceDiscountReturn", "SourceDiscountReturn1").Replace("SourceDolarPerGrain", "SourceDolarPerGrain1")
                                .Replace("CustomerDiscountReturn", "SourceDiscountReturn").Replace("CustomerDolarPerGrain", "SourceDolarPerGrain");
                        }
                        else
                        {
                            responseJson = GetProductData(productIdsStr, "").Replace("TotalCount", "records").Replace("Data", "rows");
                        }
                        _param = JsonConvert.DeserializeObject<HashParam>(responseJson);
                        if (_param.GetBool("msgcode"))
                        {
                            var data = _param.GetString("data"); 
                            if (string.IsNullOrEmpty(data))
                            {
                                //其他商品返回和裸钻不一样
                                data = _param.GetString("msginfo");
                            }
                            _param = JsonConvert.DeserializeObject<HashParam>(data);
                            if (!_param.ContainsKey("result"))
                                _param.Add("result", true); 
                            responseJson = JsonConvert.SerializeObject(_param);
                        }
                    }
                    else
                    {
                        responseJson = CRetails.AllProduct(tttagKey, productIdsStr, filterUrl);
                        responseJson = responseJson.Replace("OriginUSDPerGrain", "SourceDolarPerGrain")
                                                    .Replace("OriginDiscountReturn", "SourceDiscountReturn")
                                                    .Replace("OriginUSDPerCarat", "SourceDolarPerCarat");
                    }
                    #endregion
                    //responseJson = CRetails.AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<T> product = JsonConvert.DeserializeObject<Products<T>>(responseJson);
                    List<int> UpperGoodsId = new List<int>();//非现货
                    #region 拿到设置好供应商的账号 
                    IList<OtherSystemLoginInfo> otherSystemLoginInfos = YZ.GetDatabase(tttagKey).QueryForList<OtherSystemLoginInfo>("Supplier.GetOtherSystemLoginInfoBySupplier", null);
                    Dictionary<string, NextSupplierGoodsID> dictOtherSystemLoginInfo = new Dictionary<string, NextSupplierGoodsID>();
                    List<int> NextGoodsId = new List<int>();//非现货
                    #endregion
                    foreach (dynamic item in product.Rows)
                    {
                        //判断是否是现货
                        if (item.Supplier == tttagKey)
                        {
                            listId.Add((int)item.ID);
                        }
                        else
                        {
                            UpperGoodsId.Add((int)item.ID);
                            if (otherSystemLoginInfos.Count > 0)
                            {
                                foreach (var itemSupplier in otherSystemLoginInfos)
                                {
                                    if (item.Supplier == itemSupplier.SupplierCode)
                                    {
                                        if (!dictOtherSystemLoginInfo.ContainsKey(item.Supplier))
                                        {
                                            NextSupplierGoodsID next = new NextSupplierGoodsID();
                                            next.Supplier = item.Supplier;
                                            next.Url = itemSupplier.Url;
                                            {//客户ID
                                                var lPostJson = new { Name = itemSupplier.UserName, Pwd = itemSupplier.Password };
                                                var requestResult = MyHttpRequest.HttpRequest(itemSupplier.Url + "/Customer/CustomerLogin", JsonConvert.SerializeObject(lPostJson));
                                                requestResult = requestResult.Substring(1, requestResult.Length - 2);
                                                int customerId = 0;
                                                requestResult = requestResult.Replace("\\", "");
                                                RetailResultInfo param1 = JsonConvert.DeserializeObject<RetailResultInfo>(requestResult);
                                                if (param1 != null && param1.data != null)
                                                {
                                                    customerId = param1.data.CustomerID;
                                                    next.CustomerID = customerId;
                                                }
                                            }
                                            next.inventoryList = item.ID.ToString();
                                            dictOtherSystemLoginInfo.Add(item.Supplier, next);
                                        }
                                        else
                                        {
                                            NextSupplierGoodsID next = dictOtherSystemLoginInfo[item.Supplier];
                                            next.inventoryList = next.inventoryList + "," + item.ID.ToString();
                                            dictOtherSystemLoginInfo[item.Supplier]= next;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ErjiToYijiProductResult productResult = null;
                    #region 下一级的现货要去下一级下单
                    if (dictOtherSystemLoginInfo.Count > 0)
                    {
                        foreach (var itemSupplier in dictOtherSystemLoginInfo)
                        {
                            //{"CustomerID":"3","OnShelves":1,"InventoryList":[{"InventoryIDs":["10499679"],"GoodsTypeID":1},{"InventoryIDs":["65594"],"GoodsTypeID":3}]}
                            NextSupplierGoodsID next = itemSupplier.Value;

                            var inventoryList = new { InventoryIDs = Array.ConvertAll<string,int>(next.inventoryList.Split(','),int.Parse) , GoodsTypeID = goodsType };
                            var inventoryListArr = new List<dynamic>();
                            inventoryListArr.Add(inventoryList);
                            var orderParam = new
                            {
                                CustomerID= next.CustomerID,
                                OnShelves = 1,
                                InventoryList = inventoryListArr,
                                Mark = "lingshou"
                            };
                            var result = MyHttpRequest.HttpRequest(next.Url + "/service/SubmitOrders", JsonConvert.SerializeObject(orderParam));
                            result = result.Replace(@"\", "");
                            result = result.Substring(1, result.Length - 2);
                            productResult = JsonConvert.DeserializeObject<ErjiToYijiProductResult>(result);
                        }
                    }
                    #endregion
                    #region 非现货要去上一级下单
                    var firstLevelKey = tttagKey.Split(new string[] { "__" }, StringSplitOptions.None)[0]; //一级对应的key
                    if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")//二级特有标识
                    { 
                        if (UpperGoodsId.Count > 0)
                        {
                            if (param["ErJiMark"].ToString() == "2LSto1LS")
                            {
                                //{"CustomerID":"3","OnShelves":1,"InventoryList":[{"InventoryIDs":["10499679"],"GoodsTypeID":1},{"InventoryIDs":["65594"],"GoodsTypeID":3}]}
                                var inventoryList = new { InventoryIDs = UpperGoodsId.ToArray<int>(), GoodsTypeID = goodsType };
                                var inventoryListArr = new List<dynamic>();
                                inventoryListArr.Add(inventoryList);

                                var orderParam = new
                                {
                                    ParentKey = param["ParentKey"].ToString(),
                                    PublicParentUrl = param["PublicParentUrl"].ToString(),
                                    OnShelves = 1,
                                    InventoryList = inventoryListArr
                                };
                                var result = SubmitOrdersFromSub(JsonConvert.SerializeObject(orderParam));
                                result = result.Replace(@"\", "");
                                result = result.Substring(1, result.Length - 2);
                                productResult = JsonConvert.DeserializeObject<ErjiToYijiProductResult>(result);
                            }
                            else if (param["ErJiMark"].ToString() == "2LSto1PF")
                            { 
                                HashParam yijiOrderParam = new HashParam();
                                yijiOrderParam.Add("TagKey", firstLevelKey);//取对应上级的KEY
                                yijiOrderParam.Add("GoodsType", goodsType);
                                yijiOrderParam.Add("ProductIDs", UpperGoodsId);
                                yijiOrderParam.Add("OrderType", "2");
                                yijiOrderParam.Add("SecondSN", tttagKey);
                                var yiJiResult = SubmitOrderByYiJi(JsonConvert.SerializeObject(yijiOrderParam), token).Result;
                                productResult = JsonConvert.DeserializeObject<ErjiToYijiProductResult>(yiJiResult);
                               
                            }
                        }
                    }
                    #endregion

                     
                     
                    if (product.Rows.Count > 0)
                    {
                        if (_productIDs.Length - product.Rows.Count > 0)
                        {
                            failCount1 = _productIDs.Length - product.Rows.Count;//被抢购的数量
                        }
                        //批量删除购物车及生成订单 事务
                        #region   提交订单 
                        // DiamondsPriceHandler diamondspricehandlers = new DiamondsPriceHandler();
                        foreach (dynamic item in product.Rows)
                        {

                            bool isSpotGoods = (item.Supplier == tttagKey); //是现货
                            HashParam hsParam = new HashParam();
                            hsParam.Add("InventoryID", (int)item.ID);
                            hsParam.Add("CustomerID", customer.CustomerID);
                            hsParam.Add("GoodsTypeID", goodsType);
                            OrderInfo _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.SelectOrderByCustomer", hsParam);//OrderIDs 
                            if (_order != null)
                            {
                                //只有裸钻的订单要判断（数量=1），其他商品的数量>1   所以不用判断
                                //已经存在的订单
                                failCount++;
                                continue;
                            }
                            //订单 
                            OrderInfo order = new OrderInfo();
                            if (item.Supplier == tttagKey)
                            {
                                DateTime.TryParse(item.ArrivalTime, out DateTime arrivalTime);
                                order.ArrivalTime = arrivalTime;

                                if (order.ArrivalTime != null)
                                    order.OrderStatus = 3;//待出货
                                else
                                    order.OrderStatus = 2;//待到货
                                //裸钻现货
                                if (goodsType == GoodsType.Diamond)
                                {
                                    order.BuyDis = item.PurchaseDiscountReturn;
                                    order.BuyRMBPrice = Math.Round(item.PurchaseRMB, 3);
                                    order.BuyUSDPrice = Math.Round(item.PurchaseUSDPerGrain, 3);
                                }
                                if (item.PurchaseExchange != null && item.PurchaseExchange > 0)
                                {
                                    order.BuyExchangerate = item.PurchaseExchange;
                                }
                                else
                                {
                                    order.BuyExchangerate = 0;
                                }
                            }
                            else
                            {
                                if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")//一级不需要这部检查
                                {
                                    if (productResult != null && productResult.msginfo.SuccessList.Contains((int)item.ID))
                                    {
                                        if (item.Supplier == firstLevelKey) //如果是一级的现货
                                        {
                                            order.OrderStatus = 2;//待到货
                                        }
                                        else
                                        {
                                            order.OrderStatus = 1;//待采购
                                        }
                                    }
                                    else
                                    {
                                        //不包含的上家的货就是失败了的
                                        continue;
                                    }
                                } 
                                else
                                {
                                    order.OrderStatus = 1;//待采购
                                }
                            } 
                            
                            order.GoodsTypeID = goodsType;
                            order.InventoryID = (int)item.ID;
                            order.Supplier = item.Supplier;
                            order.CustomerID = customer.CustomerID;
                            order.AddressID = Convert.ToInt16(param["AddressID"]);
                            order.UserID = param["UserID"] != null ? int.Parse(param["UserID"].ToString()) : 0;
                            order.Remarks = param["Remarks"] != null ? param["Remarks"].ToString() : "";
                            order.PurchaseExchangerate = GetPurchaseExchangeRate(setting);//采购汇率   
                            order.SalesExchangerate = GetRate(setting);//销售汇率 
                            if (goodsType == GoodsType.Diamond)
                            {
                                order.InventoryCount = 1;
                                order.Rapnet = item.Rapnet;
                                //计算裸钻的价格
                                order.InventoryAttribute = JsonConvert.SerializeObject(item);
                                CalcProductOrderPrice(tttagKey, customer, setting, ref order);
                                DateTime.TryParse(item.PurchaseTime, out DateTime buyPurchaseTime);
                                order.BuyPurchaseTime = buyPurchaseTime;

                                order.PaymentStatus = item.ReceiptStatus;//付款状态  数据中心过来是付款状态， 这里是一个坑
                                order.BuyPurchaseSupplier = item.PurchaseSupplier;//采购供应商
                            }
                            else if (goodsType == GoodsType.Parcel)
                            {
                                order.InventoryCount = 1;
                                order.PurchaseUSD = item.Price;
                                order.PurchaseRMB = order.PurchaseUSD * order.PurchaseExchangerate;
                                //全局商品的倍率
                                //decimal settingRate = GetGroupAmount(setting, item.Price);
                                decimal settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, item.Price, tttagKey);
                                //供应商的倍率
                                decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, order.Supplier, order.GoodsTypeID);
                                //客户的折扣 *全局商品的倍率 * 供应商的倍率

                                order.ConfirmUSD = order.PurchaseUSD * settingRate * supplierRate * customer.Discounts;
                                order.ConfirmRMB = order.ConfirmUSD * order.SalesExchangerate;
                                order.InventoryAttribute = JsonConvert.SerializeObject(item);
                            }
                            else if (goodsType == GoodsType.PrimeGolds)
                            {
                                order.InventoryCount = 1;
                                order.PurchaseRMB = item.TotalWeight * item.GoldPrice + item.TotalWeight * item.LaborFee;
                                order.PurchaseUSD = order.PurchaseRMB / order.PurchaseExchangerate;//原RMB价/采购汇率 
                                //全局商品的倍率
                                //decimal settingRate = GetGroupAmount(setting, order.PurchaseRMB.Value);
                                decimal settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, item.Price, tttagKey);
                                //供应商的倍率
                                decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, order.Supplier, order.GoodsTypeID);

                                order.ConfirmRMB = order.PurchaseRMB * settingRate * supplierRate * customer.Discounts;
                                order.ConfirmUSD = order.ConfirmRMB / order.SalesExchangerate;
                                order.InventoryAttribute = JsonConvert.SerializeObject(item);
                            }
                            else if (goodsType == GoodsType.InlaySettings)
                            {
                                if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")
                                {
                                    item.GoldPrice = item.CustomerGoldPrice;
                                    item.Wastage = item.CustomerWastage;
                                    item.SideLaborFee = item.CustomerSideLaborFee;
                                    item.LaborFee = item.CustomerLaborFee;
                                    item.SidePrice = item.CustomerSidePrice;
                                    item.Insurance = item.CustomerInsurance;
                                }

                                order.InventoryCount = 1;
                                order.PurchaseRMB = (Convert.ToDecimal(item.GoldPrice) * Convert.ToDecimal(item.NetGoldWeight) * (1 + Convert.ToDecimal(item.Wastage))) +
                                    Convert.ToDecimal(item.SideLaborFee) * Convert.ToDecimal(item.SideNum) + Convert.ToDecimal(item.SidePrice) + Convert.ToDecimal(item.LaborFee) + Convert.ToDecimal(item.Insurance);

                                //(item.GoldPrice * item.NetGoldWeight * (1 + item.Wastage)) + item.SideLaborFee * item.SideNum + item.SidePrice + item.LaborFee + item.Insurance;//原卖价
                                order.PurchaseUSD = order.PurchaseRMB / order.PurchaseExchangerate;//原RMB价/采购汇率
                                //全局商品的倍率
                                //decimal settingRate = GetGroupAmount(setting, order.PurchaseRMB.Value);
                                decimal settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, item.Price, tttagKey);
                                //供应商的倍率
                                decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, order.Supplier, order.GoodsTypeID);

                                order.ConfirmRMB = order.PurchaseRMB * settingRate * supplierRate * customer.Discounts;
                                item.Price = order.ConfirmRMB.Value;
                                order.ConfirmUSD = order.ConfirmRMB / order.SalesExchangerate;

                                decimal resultDisc = (1 + (supplierRate - 1) + (settingRate - 1));

                                if (settingRate * supplierRate != 1)
                                {
                                    //反推出最后的结果
                                    item.CustomerGoldPrice = Math.Round(item.GoldPrice * resultDisc);//金价
                                    item.CustomerWastage = item.Wastage;//损耗
                                    item.CustomerSideLaborFee = Math.Round(item.SideLaborFee * resultDisc);//副石工费
                                    item.CustomerLaborFee = Math.Round(item.LaborFee * resultDisc);//工费
                                    item.CustomerSidePrice = Math.Round(item.SidePrice * resultDisc);//副石总额
                                    item.CustomerInsurance = Math.Round(item.Insurance * resultDisc); //保险费 
                                }
                                else
                                {
                                    item.CustomerGoldPrice = item.GoldPrice * resultDisc;//金价
                                    item.CustomerWastage = item.Wastage;//损耗
                                    item.CustomerSideLaborFee = item.SideLaborFee * resultDisc;//副石工费
                                    item.CustomerLaborFee = item.LaborFee * resultDisc;//工费
                                    item.CustomerSidePrice = item.SidePrice * resultDisc;//副石总额
                                    item.CustomerInsurance = item.Insurance * resultDisc; //保险费 
                                }
                                order.InventoryAttribute = JsonConvert.SerializeObject(item);
                            }
                            else
                            { 
                                order.InventoryCount = 1;
                                order.PurchaseRMB = item.Price;
                                //全局商品的倍率
                                //decimal settingRate = GetGroupAmount(setting, item.Price);
                                decimal settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, item.Price, tttagKey);
                                //供应商的倍率
                                decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, order.Supplier, order.GoodsTypeID);
                                //客户的折扣 *全局商品的倍率 * 供应商的倍率
                                order.ConfirmRMB = order.PurchaseRMB * settingRate * supplierRate * customer.Discounts;
                                //order.InventoryCount = 1;
                                order.InventoryAttribute = JsonConvert.SerializeObject(item);
                            }
                            //判断是否是现货 ，现货不用提交到一级 
                            var strAttribute = order.InventoryAttribute;
                            order.CreateTime = DateTime.Now;
                            using (ITransaction trans_addorder = YZ.GetTransaction(tttagKey))
                            {
                                int addOrderResult = trans_addorder.Add(order);
                                if (addOrderResult > 0)
                                {
                                    listScuccess.Add(order.InventoryID.Value);

                                    #region 现货，则更新

                                    if (isSpotGoods)
                                    {
                                        try
                                        {
                                            var result = "";
                                            Hashtable newParam = new Hashtable();
                                            //提交数据中心 更新统包的重量
                                            if (goodsType == GoodsType.Diamond)
                                            {
                                                TransmissionOrderResult submitOrderResult = AllPublic.OprationOrders(listId.ToArray(), "add", tttagKey);//提交订单 InventoryID  (OprationOrders 包含了提交订单、删除订单 和获取订单)
                                                if (submitOrderResult != null && submitOrderResult.Successful != null && submitOrderResult.Failed != null)
                                                {
                                                    successCount1 = submitOrderResult.Successful.Length;
                                                    failCount1 = submitOrderResult.Failed.Length;
                                                }
                                                failCount = failCount1;
                                            }
                                            else if (goodsType == GoodsType.Parcel)
                                            {
                                                Parcels parcel = Json.Deserialize<Parcels>(strAttribute);
                                                parcel.Weight = parcel.Weight - order.InventoryCount.Value;
                                                if (parcel.Weight < 0)
                                                {
                                                    failCount++;
                                                }
                                                else
                                                {
                                                    newParam.Add("Weight", parcel.Weight.ToString());
                                                    strAttribute = JsonConvert.SerializeObject(newParam);
                                                    result = CRetails.AllProduct(tttagKey, strAttribute, string.Format(GlobalConfig.TransmissionParcelOprateUrl, parcel.ID), "put");
                                                }
                                            }
                                            else if (goodsType == GoodsType.Ring)//成品 素金 需要更新现货与定制状态
                                            {

                                                Ring ring = Json.Deserialize<Ring>(strAttribute);
                                                if (ring.IsStock == 1)
                                                {
                                                    newParam.Add("IsStock", "2");//2  就是定制，1 就是现货
                                                    strAttribute = JsonConvert.SerializeObject(newParam);
                                                    result = CRetails.AllProduct(tttagKey, strAttribute, string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ring.ID), "put");
                                                }

                                            }
                                            else if (goodsType == GoodsType.PrimeGolds)
                                            {

                                                PrimeGolds primegolds = Json.Deserialize<PrimeGolds>(strAttribute);
                                                primegolds.StockNumber = primegolds.StockNumber - (int)order.InventoryCount;
                                                if (primegolds.StockNumber < 0)
                                                {
                                                    failCount++;
                                                }
                                                else
                                                {
                                                    newParam.Add("StockNumber", primegolds.StockNumber.ToString());
                                                    strAttribute = JsonConvert.SerializeObject(newParam);
                                                    result = CRetails.AllProduct(tttagKey, strAttribute, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, primegolds.ID), "put");
                                                }

                                            }
                                            else if (goodsType == GoodsType.InlaySettings)//空托
                                            {
                                                InlaySettings inlaySettings = Json.Deserialize<InlaySettings>(strAttribute);
                                                if (inlaySettings.IsStock == 1)
                                                {
                                                    newParam.Add("IsStock", "2");//2  就是定制，1 就是现货 
                                                    strAttribute = JsonConvert.SerializeObject(newParam);
                                                    result = CRetails.AllProduct(tttagKey, strAttribute, string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, inlaySettings.ID), "put");
                                                }
                                            }
                                            else
                                            {

                                                //翡翠，彩宝  删除数据中心库存
                                                string delIds = CRetails.GetIdsStrParamByIds(new int[order.InventoryID ?? 0]);
                                                result = CRetails.AllProduct(tttagKey, delIds, filterUrl, "delete");

                                            }

                                            if (result.Equals("{\"result\": true}") || ("").Equals(result))
                                            {
                                                //移除购物车
                                                int[] cartIds = { order.InventoryID ?? 0 };
                                                DelCartInfo(goodsType, order.CustomerID ?? 0, cartIds, tttagKey);
                                                successCount++;
                                                trans_addorder.CommitTransaction();//提交事务 
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            successCount1--;
                                            failCount++;
                                            throw;
                                        }
                                    }
                                    else
                                    { 
                                        int[] cartIds = { order.InventoryID ?? 0 };
                                        DelCartInfo(goodsType, order.CustomerID ?? 0, cartIds, tttagKey);
                                        successCount++;
                                        trans_addorder.CommitTransaction();//提交事务 
                                    }
                                    #endregion

                                }
                                else
                                {
                                    failCount++; 
                                }
                            }

                        }

                        #endregion

                        if (successCount > 0)//成功则发送短信
                        {
                        }
                        if (successCount == 0 && successCount1 == 0 && failCount == 0 && failCount1 == 0)
                        {
                            failCount = listId.Count;
                        }
                        var msg = new
                        {
                            Successful = successCount,
                            Successful1 = successCount1,
                            Failed = failCount,
                            Failed1 = failCount1,
                            SuccessList = listScuccess,//其实这里的现货字典才是所需要的，非现货可以不用理会
                            FailList = ""
                        };
                        var orderInfoMessage = JsonConvert.SerializeObject(msg); 
                        return CommonLog.MsgSuccessObj(orderInfoMessage); 
                    }
                    else
                    {
                        var msg = new
                        {
                            Successful = 0,
                            Successful1 = 0,
                            Failed = 0,
                            Failed1 = _productIDs.Length,
                            SuccessList = listScuccess,//其实这里的现货字典才是所需要的，非现货可以不用理会
                            FailList = ""
                        };
                        var orderInfoMessage = JsonConvert.SerializeObject(msg);
                        return CommonLog.MsgSuccessObj(orderInfoMessage);

                    }
                }
                else
                {
                    var msg = new
                    {
                        Successful = 0,
                        Successful1 = 0,
                        Failed = 0,
                        Failed1 = 0,
                    };
                    var orderInfoMessage = JsonConvert.SerializeObject(msg);
                    return CommonLog.MsgSuccessObj(orderInfoMessage);
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                //return CommonLog.MsgErrorInfo("程序错误"); 
                var msg = new
                {
                    Successful = 0,
                    Successful1 = 0,
                    Failed = 0,
                    Failed1 = 0,
                    SuccessList = listScuccess,//其实这里的现货字典才是所需要的，非现货可以不用理会
                    FailList = ""
                };
                var orderInfoMessage = JsonConvert.SerializeObject(msg);
                return CommonLog.MsgSuccessObj(orderInfoMessage);
            }
        }
        /// <summary>
        /// 计算裸钻价格
        /// </summary>
        /// <param name="order"></param>
        /// <param name="customer"></param>
        public void CalcProductOrderPrice(string tttagKey, CustomerInfo customer, SysSettingInfo setting, ref OrderInfo order)
        {
            if (order == null)
            {
                return;
            }
            try
            {
                string attr = order.InventoryAttribute.Replace("OriginUSDPerGrain", "SourceDolarPerGrain").Replace("OriginDiscountReturn", "SourceDiscountReturn").Replace("OriginUSDPerCarat", "SourceDolarPerCarat");
                InventoryResult item = JsonConvert.DeserializeObject<InventoryResult>(attr);

                decimal sourceDisc = 0;//临时退点

                decimal tempDouble = 1; //临时存储白或彩的倍率
                //彩钻
                if (item.IsFancy == 1)
                {
                    //if (tttagKey.Contains("_"))
                    //    sourceDisc = customer.FancyRebate.Value;
                    //分析4c折扣-彩钻
                    IList<Group_4C> lv2FancyDiss = GetGroupCCCC(2, setting.GroupFancy4C); //2为彩 ,1 为白
                    decimal globalDis = 0;// GoodsType.GetGlobalFancyDiscountReturn(setting); 
                    //分组彩
                    if (lv2FancyDiss != null)
                    {
                        var shape = 0;  //存储异形或圆形
                        foreach (var item2 in lv2FancyDiss)
                        {
                            int sha = item2.Shape == "round" ? 1 : 2;
                            //item.Weight   0.31-0.36
                            decimal minWeight = item2.MinWeight;
                            decimal maxWeight = item2.MaxWeight;
                            shape = item.Shape > 1 ? 2 : 1;  //设置为圆形或者异形
                            shape = item.Shape == 1 ? 1 : 2;  //设置为圆形或者异形
                            if (shape == sha && item.Weight >= minWeight && item.Weight <= maxWeight)
                            {
                                ///全局折扣+=加上分组折扣(彩)
                                globalDis = globalDis + item2.Dis;
                                tempDouble = item2.Double == 0 ? 1 : item2.Double;   //有分组倍率，则全局*分组  合并为全局倍率
                                break;
                            }
                        }
                    }
                    sourceDisc += Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, item.Supplier).FancyRebate.Value;
                    //彩钻价格计算
                    item.DiscountReturn = globalDis + sourceDisc;
                    order.PurchaseReturn = item.DiscountReturn;
                    item.DolarPerGrain = (decimal)item.SourceDolarPerGrain * (decimal)((100 + sourceDisc) / 100) * (decimal)((100 + globalDis) / 100) * tempDouble; //只在粒上乘以倍率
                    //原美金价格 & RMB
                    order.PurchaseUSD = item.DolarPerGrain;
                    order.PurchaseRMB = item.DolarPerGrain * order.PurchaseExchangerate;
                    if (customer != null)
                    {
                        order.ConfirmUSD = (decimal)(item.SourceDolarPerGrain * (decimal)((100 + globalDis) / 100) * (decimal)((100 + sourceDisc) / 100) * (decimal)((100 + customer.FancyRebate.Value) / 100)) * tempDouble; //只在粒上乘以倍率
                        order.ConfirmRMB = order.ConfirmUSD * order.SalesExchangerate;
                    }
                }
                //白钻价格
                else
                {
                    //if (tttagKey.Contains("_"))
                    //    sourceDisc = customer.Rebate.Value;
                    //分析4c折扣-白钻
                    IList<Group_4C> lv2Diss = GetGroupCCCC(1, setting.Group4C);  //2为彩 ,1 为白//白钻分组数据(匹配成想要的格式)
                    //分组白
                    if (lv2Diss != null)
                    {
                        var shape = 0;  //存储异形或圆形
                        foreach (var item2 in lv2Diss)
                        {
                            int sha = item2.Shape == "round" ? 1 : 2; //规则

                            //item.Weight   0.31-0.36

                            decimal minWeight = item2.MinWeight;
                            decimal maxWeight = item2.MaxWeight;
                            shape = item.Shape > 1 ? 2 : 1;  //设置为圆形或者异形
                            if (shape == sha && item.Weight >= minWeight && item.Weight <= maxWeight)
                            {
                                //全局折扣+=加上分组折扣(白)
                                sourceDisc += item2.Dis;
                                tempDouble = item2.Double == 0 ? 1 : item2.Double;  //有分组倍率，则全局*分组  合并为全局倍率
                                break;
                            }
                        }
                    }

                    sourceDisc += item.SourceDiscountReturn.Value;
                    //原退点 +当前供应商的退点
                    sourceDisc += Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, item.Supplier).Rebate.Value;
                    //原退点 +当前供应商的退点 +全局退点
                    //sourceDisc += GoodsType.GetGlobalDiscountReturn(setting);
                    //discount=CalcWhiteReturnPoint(
                    item.DiscountReturn = sourceDisc;
                    //美金克拉价格
                    item.DolarPerCarat = (decimal)(item.Rapnet * ((100 + sourceDisc) / 100)) * tempDouble;
                    item.DolarPerGrain = item.DolarPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率
                    //原美金价格
                    order.PurchaseUSD = item.DolarPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率
                    order.PurchaseRMB = order.PurchaseUSD * order.PurchaseExchangerate;
                    order.PurchaseReturn = CalcWhiteReturnPoint(0, item.DolarPerGrain, item.Rapnet, item.Weight, 1, 0);
                    //客户看到的价格
                    if (customer != null)
                    {
                        //按退点计算
                        if (customer.IsRebate == 1 || customer.IsRebate == null)
                        {
                            //计算客户价格--白钻   //原退点 +当前供应商的退点 +全局退点+客户退点 
                            decimal CustomerDolarPerGrain = (decimal)(item.Rapnet * (decimal)((100 + Convert.ToDecimal(sourceDisc) + customer.Rebate) / 100)) * tempDouble * (decimal)item.Weight.Value;
                            order.ConfirmUSD = CustomerDolarPerGrain * customer.Discounts;
                            order.ConfirmRMB = order.ConfirmUSD * order.SalesExchangerate;
                            //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                            order.SalesReturn = CalcWhiteReturnPoint(0, CustomerDolarPerGrain, item.Rapnet, item.Weight, 1, 0);
                        }
                        else if (customer.IsRebate == 0)
                        {
                            decimal CustomerDolarPerGrain = (decimal)(item.Rapnet * (decimal)((100 + Convert.ToDecimal(sourceDisc)) / 100)) * tempDouble * (decimal)customer.Rebate * (decimal)item.Weight.Value;
                            order.ConfirmUSD = CustomerDolarPerGrain * customer.Discounts;
                            order.ConfirmRMB = order.ConfirmUSD * order.SalesExchangerate;
                            order.SalesReturn = CalcWhiteReturnPoint(0, CustomerDolarPerGrain, item.Rapnet, item.Weight, 1, 0);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                order.PurchaseUSD = 0;
                order.PurchaseRMB = 0;
                order.ConfirmUSD = 0;
                order.ConfirmRMB = 0;
            }
        }
        //分析4c折扣
        public static IList<Group_4C> GetGroupCCCC(int lib, string str)
        {
            if (str == null || str == "" || str.Trim().Length < 1) return null;
            else
            {
                if (System.Web.HttpContext.Current.Cache.Get("Cache:Group4C" + lib.ToString()) == null)
                {
                    str = str.TrimEnd(';');//去多组合的末尾;

                    string[] obj = str.Replace("\n", "").Replace("\r", "").Split(';');  //分组存相对应的折扣
                    IList<Group_4C> lv2CCCCs = new List<Group_4C>();

                    //1.形状
                    for (int i = 0; i < obj.Length; i++)
                    {
                        Group_4C lv2CCCC = new Group_4C();
                        //round 0.30-0.39 h si1 2;
                        string[] temps = obj[i].Replace("white#", "").Replace("fancy#", "").Split('#');
                        if (temps.Length > 1)
                        {
                            lv2CCCC.Shape = temps[0];
                            //2.重量
                            if (temps[1].Contains("-"))
                            {
                                var weights = temps[1].Split('-');
                                lv2CCCC.MinWeight = Convert.ToDecimal(weights[0]);
                                lv2CCCC.MaxWeight = Convert.ToDecimal(weights[1]);
                            }
                            else
                            {
                                lv2CCCC.MinWeight = 0.01M;
                                lv2CCCC.MaxWeight = 999.99M;
                            }

                            lv2CCCC.Double = temps[2] == "" ? 1 : Convert.ToDecimal(temps[2]);
                            lv2CCCC.Dis = temps[3] == "" ? 0 : Convert.ToDecimal(temps[3]);
                            lv2CCCCs.Add(lv2CCCC);
                        }
                    }
                    //第一次访问5分钟后过期，免得修改了4c或金额得改缓存设置
                    System.Web.HttpContext.Current.Cache.Insert("Cache:Group4C" + lib.ToString(), lv2CCCCs, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
                    return lv2CCCCs;
                }
                else
                {
                    return System.Web.HttpContext.Current.Cache.Get("Cache:Group4C" + lib.ToString()) as IList<Group_4C>;
                }

            }
        }


        /// <summary>
        /// 获取商品的全局倍率
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        /// 9999.99-#1.5#;10000-19999.99#2#;20000-49999.99#3#;
        public decimal GetGroupAmount(SysSettingInfo setting, decimal price)
        {
            decimal rate = 1;
            if (!string.IsNullOrEmpty(setting.GroupAmount))
            {
                string[] groupAmountList = setting.GroupAmount.Split(';');
                for (int i = 0; i < groupAmountList.Length; i++)
                {
                    //10000-19999.99#2#
                    string[] list = groupAmountList[i].TrimEnd('#').Split('#')[0].Split('-'); 
                    if (list.Length == 2 && !string.IsNullOrEmpty(list[1]))
                    {
                        if (Convert.ToDecimal(price) >= Convert.ToDecimal(list[0]) && Convert.ToDecimal(price) <= Convert.ToDecimal(list[1]))
                        {
                            rate = Convert.ToDecimal(groupAmountList[i].TrimEnd('#').Split('#')[1]);
                            break;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(groupAmountList[i]))
                            rate = Convert.ToDecimal(groupAmountList[i].TrimEnd('#').Split('#')[1]);
                        else
                            rate = 1;
                        break;
                    }

                }
            }
            return rate;
        }

        
        /// <summary>
        /// 查询订单根据条件
        /// </summary>
        /// <param name="selectParam"></param>
        /// <returns></returns>
        public string GetAllOrdersList(string strParam)
        {
            logParam = strParam;
            string tttagKey = CommonUrl.getURL(null, strParam);
            //Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(strParam));
            HashParam param = Json.Deserialize<HashParam>(strParam);
            if (param.GetInt("CustomerID", 0) == 0)
            {
                return CommonLog.MsgErrorInfo("参数不正确");
            }
            else
            {
                IList<OrderInfo> list = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrders", param);
                if (list != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
                }
                return CommonLog.MsgErrorInfo("未查询到订单");
            }
        }
        /// <summary>
        /// 团队查询订单
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetTeamOrdersList(string strParam)
        {
            logParam = strParam;
            string tttagKey = CommonUrl.getURL(null, strParam);
            Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(strParam));

            IList<OrderResultList> list = YZ.GetDatabase(tttagKey).QueryForList<OrderResultList>("Order.GetTeamOrdersList", param);
            if (list != null)
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
            }
            return CommonLog.MsgErrorInfo("未查询到订单");
        }
        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="selectParam"></param>
        /// <returns></returns>
        public string UpdateProductsOrder(string strParam)
        {
            return AllPublic.UpdateProductsOrder(strParam);
        }
        public string AddSupplierRole(string param)
        {
            return CWholesalers.OptionSupplierRole(param, "add");
        }

        /// <summary>
        /// 全局设置
        /// </summary>
        /// <param name="tType"></param>
        /// <param name="GoodtypeId"></param>
        /// <returns></returns>
        public static SysSettingInfo GetSystemSetting(int tType, int GoodtypeId, string tttagKey)
        {
            SysSettingInfo setting = new SysSettingInfo();
            Hashtable hash = new Hashtable();
            hash.Add("SysSettingID", GoodtypeId);
            setting = YZ.GetDatabase(tttagKey).QueryForObject<SysSettingInfo>("Syssetting.GetSetting", hash);
            return setting;
        }
        /// <summary>
        /// 全局销售汇率 -裸钻
        /// </summary>
        /// <returns></returns>
        public static decimal GetRate(SysSettingInfo setting)
        {
            if (setting.Rate.HasValue && setting.Rate > 0)
            {
                return setting.Rate.Value;
            }
            return 1;
        }


        /// <summary>
        /// 全局采购汇率 - 裸钻
        /// </summary>
        /// <returns></returns>
        public static decimal GetPurchaseExchangeRate(SysSettingInfo setting)
        {
            if (setting.PurchaseExchangerate.HasValue && setting.PurchaseExchangerate > 0)
            {
                return setting.PurchaseExchangerate.Value;
            }
            return 1;
        }


        /// <summary>
        /// 全局白钻退点
        /// </summary>
        /// <returns></returns>
        public static decimal GetGlobalDiscountReturn(SysSettingInfo setting)
        {
            if (setting.GlobalDiscountReturn.HasValue)
            {
                return setting.GlobalDiscountReturn.Value;
            }
            return 0;
        }

        /// <summary>
        /// 全局彩钻退点
        /// </summary>
        /// <returns></returns>
        public static decimal GetGlobalFancyDiscountReturn(SysSettingInfo setting)
        {
            if (setting.GlobalFancyDiscountReturn.HasValue)
            {
                return setting.GlobalFancyDiscountReturn.Value;
            }
            return 0;
        }
        /// <summary>
        /// 计算退点
        /// </summary>
        /// <param name="ConfirmUSD">美元单粒价</param>
        /// <param name="Rapnet">Rapnet</param>
        /// <param name="Weight">Weight</param>
        /// <param name="Discounts">Discounts</param>
        /// <param name="SourceDolarPerGrain">原单粒价</param>
        /// <returns></returns>
        public static decimal? CalcWhiteReturnPoint(int IsFancy, decimal? ConfirmUSD, decimal? Rapnet, decimal? Weight, decimal? Discounts, decimal? SourceDolarPerGrain)
        {
            decimal? ReturnPoint = 0;
            if (IsFancy != 1)
            {
                //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                ReturnPoint = ConfirmUSD * Discounts / Weight * 100 / Rapnet - 100;
            }
            else
            {
                //美元单粒价 		= 原单粒价 * (100 + 退点) / 100   
                ReturnPoint = ConfirmUSD * Discounts * 100 / SourceDolarPerGrain - 100;
            }
            return ReturnPoint;
        }



        /// <summary>
        /// 团队--优惠
        /// </summary>
        /// <param name="reviseOrdersParam"></param>
        /// <returns></returns>
        public string ReviseOrders(string reviseOrdersParam)
        {

            logParam = reviseOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(reviseOrdersParam);
            string tttagKey = CommonUrl.getURL(param, reviseOrdersParam);

            //OrderIDs（必传）、SalesExchangerate(默认值,必填)、Rebate（退点/返点法）、Discount(折扣法)(二选一)
            try
            {
                if (param.ContainsKey("OrderIDs"))
                {
                    string[] _orderIDs = param.GetString("OrderIDs").Split(',');

                    int sucessCount = 0;
                    int faildCount = 0;
                    decimal _salesExchangerate = Convert.ToDecimal(param.GetString("SalesExchangerate"));//销售汇率(默认选择系统)
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        OrderInfo _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", _orderIDs[i]);//有坑 不能用YZ.GetDatabase(tttagKey).Get<OrderInfo>()获取
                        if (_order != null)
                        {
                            try
                            {
                                InventoryInfoResult inventoryInfo = JsonConvert.DeserializeObject<InventoryInfoResult>(_order.InventoryAttribute);
                                //倍率
                                if (param.ContainsKey("Discount"))
                                {
                                    //在原基础上*折扣
                                    _order.ConfirmRMB = Math.Round(_order.ConfirmRMB.Value * param.GetDecimal("Discount").Value);
                                    _order.ConfirmUSD = _order.ConfirmRMB / _order.SalesExchangerate;
                                    _order.SalesExchangerate = _salesExchangerate;
                                    //然后通过卖出人民币总价推算卖出退点

                                    if (inventoryInfo.IsFancy == 0)
                                    {
                                        RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                                        var RapVal = rap.GetPrice(inventoryInfo);
                                        _order.SalesReturn = (((decimal)(_order.ConfirmUSD) / ((decimal)inventoryInfo.Weight * (decimal)RapVal * (decimal)_salesExchangerate)) + (-1)) * 100;
                                        inventoryInfo.CustomerDiscountReturn = _order.SalesReturn;
                                    }
                                    else
                                    {
                                        //彩钻，卖出退点为0
                                        _order.SalesReturn = 0;
                                    }
                                }
                                else if (param.ContainsKey("Rebate"))
                                {
                                    decimal _rebate = Convert.ToDecimal(param.GetString("Rebate"));//退点法(优先)    
                                    if (_salesExchangerate != 0 && _rebate != 0)
                                    {
                                        RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                                        var RapVal = rap.GetPrice(inventoryInfo);
                                        //彩钻
                                        if (inventoryInfo.IsFancy == 1)
                                        {
                                            _order.ConfirmPrice = Math.Round((decimal)_order.ConfirmPrice * ((100 + (decimal)_rebate) / 100));
                                            //卖出退点为0 
                                            _order.SalesExchangerate = _salesExchangerate;
                                        }
                                        else
                                        {
                                            //白钻
                                            //卖出退点=卖出退点+退点值
                                            _order.SalesReturn = (decimal)_order.SalesReturn + _rebate;
                                            inventoryInfo.CustomerDiscountReturn = _order.SalesReturn;
                                            _order.ConfirmRMB = Math.Round((decimal)inventoryInfo.Weight * (decimal)RapVal * ((100 + (decimal)_order.SalesReturn) / 100) * (decimal)_salesExchangerate);
                                            _order.ConfirmUSD = Math.Round((decimal)inventoryInfo.Weight * (decimal)RapVal * ((100 + (decimal)_order.SalesReturn) / 100));
                                            _order.SalesExchangerate = _salesExchangerate;
                                        }
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo("改价失败:汇率和退点不能为0");
                                    }
                                }
                                _order.InventoryAttribute = JsonConvert.SerializeObject(inventoryInfo);
                                using (ITransaction trans_reviseOrders = YZ.GetTransaction(tttagKey))
                                {
                                    int OrdersResult = trans_reviseOrders.Edit(_order);
                                    //单条成功后，就执行采购订单事务
                                    if (OrdersResult == 0)
                                    {
                                        faildCount++;
                                        trans_reviseOrders.RollBackTransaction();//回滚事务 
                                        return CommonLog.MsgErrorInfo("改价失败");
                                    }
                                    else
                                    {
                                        sucessCount++;
                                        trans_reviseOrders.CommitTransaction(); //触发入库事务  
                                    }
                                }
                            }
                            catch (Exception ex)
                            {

                                throw;
                            }
                        }
                    }
                    if (_orderIDs.Length == sucessCount)
                    {
                        return CommonLog.MsgSuccessInfo("改价成功");
                    }
                    return CommonLog.MsgErrorInfo("改价失败");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("改价失败,参数错误");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("改价：程序错误");
            }
        }
        /// <summary>
        /// 入库订单（处理（2采购成功，待入库）的订单到 (3入库成功，待出库)） --含事务   （改变订单状态 从2到3）
        /// </summary>
        /// <param name="arrivalOrdersParam"></param>
        /// <returns></returns>
        public string ArrivalOrders(string arrivalOrdersParam)
        {
            return AllPublic.ArrivalOrders<OrderInfo, CustomerInfo>(arrivalOrdersParam);
        }

        /// <summary>
        /// 取消入库
        /// </summary>
        /// <param name="cancelArrivalOrdersParam"></param>
        /// <returns></returns>
        public string CancelArrivalOrders(string cancelArrivalOrdersParam)
        {
            logParam = cancelArrivalOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(cancelArrivalOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, cancelArrivalOrdersParam);
            //OrderIDs(必填) 、ArrivalTime(必传)
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                if (_orderIDs.Length > 0)
                {
                    OrderInfo _order = new OrderInfo();
                    using (ITransaction trans_arrivalOrders = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            _order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID（OrderID） 
                            _order.OrderStatus = 2;//2 待到货      
                            _order.ArrivalTime = null;//入库时间
                            _order.ModifyTime = DateTime.Now;
                            int arrivalOrdersResult = trans_arrivalOrders.Edit(_order);
                            if (arrivalOrdersResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("取消到货失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_arrivalOrders.CommitTransaction(); //提交
                            return CommonLog.MsgSuccessInfo("取消到货成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_arrivalOrders.RollBackTransaction();//回滚
                            return CommonLog.MsgErrorInfo("取消到货失败,请尝试重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("取消到货失败,请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 修改订单运费￥ 11-11
        /// </summary>
        /// <param name="reviseOrdersParam"></param>
        /// <returns></returns>
        public string ModFreight(string freightParam)
        {
            return AllPublic.ModFreight<OrderInfo>(freightParam);
        }

        /// <summary>
        /// 制作出货单
        /// </summary>
        /// <param name="addShipParam"></param>
        /// <returns></returns>
        public string AddShip(string addShipParam)
        {
            logParam = addShipParam;
            HashParam param = Json.Deserialize<HashParam>(addShipParam);
            string tttagKey = CommonUrl.getURL(param, addShipParam);
            try
            {
                if (param.GetString("OrderIDs") != "")
                {
                    string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                    OrderInfo _order = new OrderInfo();
                    if (param.ContainsKey("ShipNo"))
                    {
                        _order.ShipNo = param["ShipNo"].ToString();//出货单页面传过来添加订单用
                    }
                    else
                    {
                        _order.ShipNo = DateTime.Now.ToString("MMddHHmmss");//出货单号MMddHHmmss
                    }
                    using (ITransaction trans_addShip = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            _order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID
                            _order.ModifyTime = DateTime.Now;
                            int addShipResult = trans_addShip.Edit(_order);
                            //单条成功后，就执行入库订单事务
                            if (addShipResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("制单失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_addShip.CommitTransaction(); //触发
                            return CommonLog.MsgSuccessInfo("制单成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_addShip.RollBackTransaction();//回滚
                            return CommonLog.MsgErrorInfo("制单失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 确认出货
        /// </summary>
        /// <param name="shipParam"></param>
        /// <returns></returns>
        public string Shipment(string shipParam)
        {
            logParam = shipParam;
            HashParam param = Json.Deserialize<HashParam>(shipParam);
            string tttagKey = CommonUrl.getURL(param, shipParam);
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                if (_orderIDs.Length > 0)
                {
                    OrderInfo _order = new OrderInfo();
                    _order.OrderStatus = 4;//4已出货
                    if (param.ContainsKey("ShipNo")) //出货单页面过来的参数
                    {
                        _order.ShipNo = param.GetString("ShipNo");
                    }
                    else
                    {
                        _order.ShipNo = DateTime.Now.ToString("MMddHHmmss");//出货单号MMddHHmmss
                    }
                    _order.ShipRemarks = param.GetString("ShipRemarks").Replace(" ", "");//出货备注
                    _order.ShipTime = DateTime.Now;//出货时间
                    _order.ModifyTime = DateTime.Now;//出货时间
                    using (ITransaction trans_shipment = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            _order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID
                            int editShipResult = trans_shipment.Edit(_order);
                            if (editShipResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("出货失败,订单标识不存在");
                            }
                        }
                        //事务
                        try
                        {
                            trans_shipment.CommitTransaction(); //提交 
                            return CommonLog.MsgSuccessInfo("出货成功\",\"shipno\":\"" + _order.ShipNo);
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_shipment.RollBackTransaction();//回滚
                            return CommonLog.MsgErrorInfo("出货失败");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("出货失败,请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }

        /// <summary>
        /// 打印出货单 9-20
        /// </summary>
        /// <param name="deliveryOrdersParam"></param>
        /// <returns></returns>
        public string GetPrintShipOrders(string printShipOrdersParam)
        {
            logParam = printShipOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(printShipOrdersParam);
            string tttagKey = CommonUrl.getURL(param, printShipOrdersParam);
            try
            {
                IList<OrderPrintResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderPrintResult>("Order.GetOrderByIDs", param);
                if (OrderList != null && OrderList.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(OrderList));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("没有找到订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 作废订单（1下单成功，采购中） --含事务     （改变订单状态 从1到10）
        /// </summary>
        /// <param name="cancelOrdersParam"></param>
        /// <returns></returns>
        public string CancelOrders(string cancelOrdersParam)
        {
            logParam = cancelOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(cancelOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, cancelOrdersParam);
            //(不足：不考虑OrderID不存在的情况,没有判断OrderID是否真实)
            //OrderIDs、SalesRemarks 取消理由(1我不想买了；2误下单，重新拍；3缺货；4货品与实际描述不符；5价格贵；)
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                if (_orderIDs.Length > 0)
                {
                    using (ITransaction trans_cancelOrders = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            //给中心发消息删除订单 2017-03-31
                            #region
                            OrderInfo _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", Convert.ToInt32(_orderIDs[i]));
                            if (_order != null && _order.InventoryID != null)
                            {
                                int[] InventoryIDs = new int[1];
                                InventoryIDs[0] = Convert.ToInt32(_order.InventoryID);//不能为空
                                TransmissionOrderResult delOrderResult = AllPublic.OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单
                            }
                            #endregion
                            _order.OrderStatus = 5;//作废订单 （5 已作废） 
                            _order.Remarks = param.GetString("Remarks").Replace(" ", "");//客户作废备注
                            _order.ModifyTime = DateTime.Now;
                            int cancelOrdersResult = trans_cancelOrders.Edit(_order);
                            //单条成功后，就执行作废订单事务
                            if (cancelOrdersResult > 0)
                            {
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("作废失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_cancelOrders.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("作废成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_cancelOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("作废失败,请尝试重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 自留变现
        /// </summary>
        /// <param name="stockOrdersParam"></param>
        /// <returns></returns>
        public string StockOrders(string stockOrdersParam)
        {
            logParam = stockOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(stockOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, stockOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_stockOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal totalMoney = 0;
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                BankInfo bankInfo = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", OrderList[i].ReceiptBankID);//flow.Account
                                //已收款1
                                if (OrderList[i].ReceiptStatus == 1)
                                {
                                    if (bankInfo.Currency == 1)
                                    {
                                        totalMoney = OrderList[i].ConfirmRMB.Value;
                                        //银行账户余额变更
                                        bankInfo.BankBalance = bankInfo.BankBalance - OrderList[i].ConfirmRMB.Value;
                                        trans_stockOrders.Edit(bankInfo);
                                        //增加流水记录

                                    }
                                    else if (bankInfo.Currency == 2)
                                    {
                                        totalMoney = OrderList[i].ConfirmUSD.Value;
                                        bankInfo.BankBalance = bankInfo.BankBalance - OrderList[i].ConfirmUSD.Value;
                                        trans_stockOrders.Edit(bankInfo);
                                    }
                                    #region 财务流水
                                    //新增流水
                                    FlowInfo flow = new FlowInfo();
                                    //金额
                                    flow.Amount = totalMoney;
                                    //收款银行
                                    flow.Account = bankInfo.BankID;
                                    //到款日期 
                                    flow.ArrivalTime = DateTime.Now;
                                    //结余
                                    flow.Balance = bankInfo.BankBalance;
                                    //客户ID
                                    flow.CustomerID = OrderList[i].CustomerID;
                                    //订单号
                                    flow.OrderIDs = param.GetString("OrderIDs");
                                    flow.Currency = bankInfo.Currency;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //申请人  
                                    flow.Status = 1;//已通过
                                    flow.Remarks = "订单号（" + OrderList[i].OrderID + "）,团队端自留退款" + (bankInfo.Currency == 1 ? "RMB" : "$") + "[" + flow.Amount + "]";
                                    flow.CreateTime = DateTime.Now;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //flow.Abstract = 1;//摘要 1充值 2消费 3退款 4提现
                                    flow.Type = 2;//
                                    trans_stockOrders.Add(flow);
                                    //客户的余额增加 
                                    #endregion

                                }
                                OrderList[i].OrderStatus = 6;//6已自留
                                OrderList[i].ReceiptStatus = 0;
                                OrderList[i].ModifyTime = DateTime.Now;
                                int editOrderStatusResult = trans_stockOrders.Edit(OrderList[i]);//更新订单事务
                                if (editOrderStatusResult > 0)
                                {
                                    //继续
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                }
                            }

                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("订单不存在");
                        }
                        try
                        {
                            //退回供应商事务
                            trans_stockOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("自留成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_stockOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("自留失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        /// <summary>
        /// 退回供应商
        /// </summary>
        /// <param name="returnOrdersParam"></param>
        /// <returns></returns>
        public string ReturnOrders(string returnOrdersParam)
        {
            logParam = returnOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(returnOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, returnOrdersParam);
            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_returnOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.GetOrderByIDs", param.GetString("OrderIDs"));//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? totalMoney = 0;
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                //已收款1
                                if (OrderList[i].ReceiptStatus == 1)
                                {
                                    OrderList[i].ReceiptStatus = 0;
                                    BankInfo bankInfo = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", OrderList[i].ReceiptBankID);//flow.Account
                                    if (bankInfo.Currency == 1)
                                    {
                                        totalMoney = OrderList[i].ConfirmRMB.Value;
                                        //银行账户余额变更
                                        bankInfo.BankBalance = bankInfo.BankBalance - OrderList[i].ConfirmRMB.Value;
                                        trans_returnOrders.Edit(bankInfo);
                                        //增加流水记录

                                    }
                                    else if (bankInfo.Currency == 2)
                                    {
                                        totalMoney = OrderList[i].ConfirmUSD.Value;
                                        bankInfo.BankBalance = bankInfo.BankBalance - OrderList[i].ConfirmUSD.Value;
                                        trans_returnOrders.Edit(bankInfo);
                                    }
                                    #region 财务流水
                                    //新增流水
                                    FlowInfo flow = new FlowInfo();
                                    //金额
                                    flow.Amount = totalMoney;
                                    //收款银行
                                    flow.Account = bankInfo.BankID;
                                    //到款日期 
                                    flow.ArrivalTime = DateTime.Now;
                                    //结余
                                    flow.Balance = bankInfo.BankBalance;
                                    //客户ID
                                    flow.CustomerID = OrderList[i].CustomerID;
                                    //订单号
                                    flow.OrderIDs = param.GetString("OrderIDs");
                                    flow.Currency = bankInfo.Currency;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //申请人  
                                    flow.Status = 1;//已通过
                                    flow.Remarks = "订单号（" + OrderList[i].OrderID + "）,团队端退回供应商已收款" + (bankInfo.Currency == 1 ? "RMB" : "$") + "[" + flow.Amount + "]";
                                    flow.CreateTime = DateTime.Now;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //flow.Abstract = 1;//摘要 1充值 2消费 3退款 4提现
                                    flow.Type = 2;// 退回供应商，银行账户要支出已经收款的订单钱
                                    trans_returnOrders.Add(flow);
                                    //客户的余额增加 
                                    #endregion 
                                }
                                //已付款
                                if (OrderList[i].PaymentStatus == 1)
                                {
                                    OrderList[i].PaymentStatus = 0;
                                    BankInfo bankInfo = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", OrderList[i].PaymentBankID);//flow.Account
                                    totalMoney = 0;
                                    if (bankInfo.Currency == 1)
                                    {
                                        totalMoney = OrderList[i].PurchaseRMB.Value;
                                        //银行账户余额变更
                                        bankInfo.BankBalance = bankInfo.BankBalance + OrderList[i].PurchaseRMB.Value;
                                        trans_returnOrders.Edit(bankInfo);
                                        //增加流水记录

                                    }
                                    else if (bankInfo.Currency == 2)
                                    {
                                        totalMoney = OrderList[i].PurchaseUSD.Value;
                                        bankInfo.BankBalance = bankInfo.BankBalance + OrderList[i].PurchaseUSD.Value;
                                        trans_returnOrders.Edit(bankInfo);
                                    }
                                    #region 财务流水
                                    //新增流水
                                    FlowInfo flow = new FlowInfo();
                                    //金额
                                    flow.Amount = totalMoney;
                                    //收款银行
                                    flow.Account = bankInfo.BankID;
                                    //到款日期 
                                    flow.ArrivalTime = DateTime.Now;
                                    //结余
                                    flow.Balance = bankInfo.BankBalance;
                                    //客户ID
                                    flow.CustomerID = OrderList[i].CustomerID;
                                    //订单号
                                    flow.OrderIDs = param.GetString("OrderIDs");
                                    flow.Currency = bankInfo.Currency;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //申请人  
                                    flow.Status = 1;//已通过
                                    flow.Remarks = "订单号（" + OrderList[i].OrderID + "）,团队端退回供应商已付款" + (bankInfo.Currency == 1 ? "RMB" : "$") + "[" + flow.Amount + "]";
                                    flow.CreateTime = DateTime.Now;
                                    flow.ApplyID = param.GetInt("UserID");
                                    //flow.Abstract = 1;//摘要 1充值 2消费 3退款 4提现
                                    flow.Type = 1;//  退回供应商，银行账户要增加已经付款的订单钱
                                    trans_returnOrders.Add(flow);
                                    //客户的余额增加 
                                    #endregion
                                }

                                OrderList[i].OrderStatus = 7;//7已退回 
                                OrderList[i].ArrivalTime = null;
                                OrderList[i].Remarks = param.GetString("SalesRemarks").Replace(" ", "");//备注 
                                OrderList[i].ModifyTime = DateTime.Now;
                                int editOrderStatusResult = trans_returnOrders.Edit(OrderList[i]);//更新订单事务
                                if (editOrderStatusResult > 0)
                                {
                                    //继续
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("失败,检查订单标识");
                                }
                            }
                        }
                        else
                        {
                            //无订单
                            return CommonLog.MsgErrorInfo("订单不存在");
                        }
                        try
                        {
                            //退回供应商事务
                            trans_returnOrders.CommitTransaction(); //提交事务
                            return CommonLog.MsgSuccessInfo("退回成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            trans_returnOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("退回失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        /// <summary>
        /// 备注订单  
        /// </summary>
        /// <param name="remarkOrdersParam"></param>
        /// <returns></returns>
        public string RemarkOrder(string remarkOrderParam)
        {
            logParam = remarkOrderParam;
            //OrderID（必传,且不能只传OrderID调用Edit）、SalesRemarks、PurchaseRemarks、GoodsRemark(三者选其一)
            HashParam param = Json.Deserialize<HashParam>(remarkOrderParam);
            string tttagKey = CommonUrl.getURL(param, remarkOrderParam);
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                if (_orderIDs.Length > 0)
                {
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        OrderInfo order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", _orderIDs[i]);//有坑 不能用YZ.GetDatabase(tttagKey).Get<OrderInfo>()获取
                        if (order != null)
                        {
                            OrderInfo _order = new OrderInfo();
                            _order.OrderID = order.OrderID;
                            if (param.GetString("Remarks") != "")
                            {
                                _order.Remarks = order.Remarks + ";" + param.GetString("Remarks");//客户备注
                            }
                            if (_order.Remarks != null)
                            {
                                using (ITransaction trans_remarkOrder = YZ.GetTransaction(tttagKey))
                                {
                                    int remarkOrderResult = trans_remarkOrder.Edit(_order);
                                    //单条成功后，就执行采购订单事务
                                    if (remarkOrderResult > 0)
                                    {
                                        try
                                        {
                                            trans_remarkOrder.CommitTransaction(); //执行事务
                                        }
                                        catch (Exception)
                                        {
                                            trans_remarkOrder.RollBackTransaction();//回滚事务
                                        }
                                    }
                                    else
                                    {
                                        return CommonLog.MsgErrorInfo("备注失败，订单标识不存在");//OrderID不存在的情况(单个操作好判断)
                                    }
                                }
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("请输入至少一项备注");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("备注失败，订单标识不存在");
                        }
                    }
                    return CommonLog.MsgSuccessInfo("备注成功");//成功
                }
                else
                {
                    return CommonLog.MsgErrorInfo("备注失败，没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("备注订单，程序错误");
            }
        }
        /// <summary>
        /// 团队 买价
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string updatePriceUSD(string param)
        {

            logParam = param;

            HashParam hsParam = Json.Deserialize<HashParam>(param);
            string tttagKey = CommonUrl.getURL(hsParam, param);
            hsParam["OrderIds"] = hsParam["OrderIds"].ToString().Split(',');
            decimal power = hsParam["power"] == null ? 1 : Convert.ToDecimal(hsParam["power"].ToString());
            using (ITransaction trans = YZ.GetTransaction(tttagKey))
            {
                try
                {
                    IList<OrderInfo> orderInfoList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderList", hsParam);//ToInt32 9-6
                    if (orderInfoList.Count > 0)
                    {
                        string ids = "";
                        for (int i = 0; i < orderInfoList.Count; i++)
                        {
                            ids += orderInfoList[i].OrderID.ToString() + ",";
                            CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(Convert.ToInt32(orderInfoList[i].CustomerID));
                            Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(orderInfoList[i].InventoryAttribute);
                            //计算
                            orderInfoList[i].PurchaseUSD = orderInfoList[i].PurchaseUSD * power;

                            RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                            var RapVal = rap.GetPrice(_inventory);
                            orderInfoList[i].PurchaseReturn = CalcWhiteReturnPoint(_inventory.IsFancy, orderInfoList[i].PurchaseUSD, RapVal, _inventory.Weight, _customerInfo.Discounts, orderInfoList[i].PurchaseUSD);//最后成交退点

                            orderInfoList[i].PurchaseRMB = Math.Round(orderInfoList[i].PurchaseUSD.Value * orderInfoList[i].SalesExchangerate.Value);//最后成交卖出人民币总价 *优惠 

                            orderInfoList[i].ModifyTime = DateTime.Now;
                            int update = trans.Edit(orderInfoList[i]);

                            if (update == 0)
                            {
                                return CommonLog.MsgErrorInfo("更新失败");
                            }
                        }
                        trans.CommitTransaction();
                        return CommonLog.MsgSuccessInfo("更新成功");
                    }
                    return CommonLog.MsgErrorInfo("更新失败");
                }
                catch
                {
                    trans.RollBackTransaction();
                    return CommonLog.MsgErrorInfo("更新失败");
                }
            }
        }

        /// <summary>
        /// 团队 采汇
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string updatePurchaseExchangerate(string param)
        {
            logParam = param;
            HashParam hsParam = Json.Deserialize<HashParam>(param);
            string tttagKey = CommonUrl.getURL(hsParam, param);

            hsParam["OrderIds"] = hsParam["OrderIds"].ToString().Split(',');
            decimal PurchaseExchangerate = hsParam["PurchaseExchangerate"] == null ? 1 : Convert.ToDecimal(hsParam["PurchaseExchangerate"].ToString());
            using (ITransaction trans = YZ.GetTransaction(tttagKey))
            {
                try
                {
                    IList<OrderInfo> orderInfoList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderList", hsParam);//ToInt32 9-6
                    if (orderInfoList.Count > 0)
                    {
                        string ids = "";
                        for (int i = 0; i < orderInfoList.Count; i++)
                        {
                            ids += orderInfoList[i].OrderID.ToString() + ",";
                            CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(Convert.ToInt32(orderInfoList[i].CustomerID));
                            orderInfoList[i].PurchaseExchangerate = PurchaseExchangerate;
                            orderInfoList[i].PurchaseRMB = (decimal)Math.Round((double)(orderInfoList[i].PurchaseUSD * orderInfoList[i].PurchaseExchangerate));//最后成交卖出人民币总价 * 采汇
                            orderInfoList[i].ModifyTime = DateTime.Now;
                            int update = trans.Edit(orderInfoList[i]);

                            if (update == 0)
                            {
                                return CommonLog.MsgErrorInfo("更新失败");
                            }
                        }
                        trans.CommitTransaction();
                        return CommonLog.MsgSuccessInfo("更新成功");
                    }
                    return CommonLog.MsgErrorInfo("更新失败");
                }
                catch
                {
                    trans.RollBackTransaction();
                    return CommonLog.MsgErrorInfo("更新失败");
                }
            }
        }

        /// <summary>
        /// 收款
        /// </summary>
        /// <param name="stockOrdersParam"></param>
        /// <returns></returns>
        public string PayAndRechargeOrders(string payOrdersParam)
        {
            logParam = payOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(payOrdersParam);
            string tttagKey = CommonUrl.getURL(param, payOrdersParam);

            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    param["OrderIds"] = param["OrderIDs"].ToString().Split(',');
                    using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderList", param);//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            int CustomerID = OrderList[0].CustomerID ?? 0;
                            decimal totalMonty = 0;
                            #region COPY PayOrders方法原来逻辑

                            BankInfo bankInfo = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetString("BankID"));//flow.Account
                            for (int i = 0; i < OrderList.Count; i++)
                            {
                                //未支付0
                                if (OrderList[i].ReceiptStatus == 0 && bankInfo != null)
                                {
                                    #region 
                                    //2.更新订单支付状态  
                                    OrderList[i].ReceiptStatus = 1;//收款状态(1已支付 0 未支付)
                                    OrderList[i].RecTime = DateTime.Now;//支付时间
                                    OrderList[i].ReceiptBankID = param.GetInt("BankID").Value;//收款银行账户ID
                                    int editOrderResult = trans_payOrders.Edit(OrderList[i]);//更新订单支付状态
                                    if (editOrderResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("失败,更新订单支付状态失败,检查订单标识");
                                    }
                                    #endregion

                                    //更新收款银行余额
                                    #region
                                    if (bankInfo != null)
                                    {
                                        if ((int)bankInfo.Currency == 1)//RMB
                                        {
                                            bankInfo.BankBalance += OrderList[i].ConfirmRMB;
                                            totalMonty += OrderList[i].ConfirmRMB.Value;
                                        }
                                        else if ((int)bankInfo.Currency == 2)
                                        {
                                            bankInfo.BankBalance += OrderList[i].ConfirmUSD;
                                            totalMonty += OrderList[i].ConfirmUSD.Value;
                                        }

                                        int editBank = trans_payOrders.Edit(bankInfo);
                                        if (editBank > 0)
                                        {
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("更新收款银行余额失败");
                                        }
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //已支付1订单
                                    return CommonLog.MsgErrorInfo("失败,订单已收款");
                                }
                            }
                            #region 财务流水
                            //新增流水
                            FlowInfo flow = new FlowInfo();
                            //金额
                            flow.Amount = totalMonty;
                            //收款银行
                            flow.Account = bankInfo.BankID;
                            //到款日期 
                            flow.ArrivalTime = DateTime.Now;
                            //结余
                            flow.Balance = bankInfo.BankBalance;
                            //客户ID
                            flow.CustomerID = CustomerID;
                            //订单号
                            flow.OrderIDs = param.GetString("OrderIDs");
                            flow.Currency = bankInfo.Currency;
                            flow.ApplyID = param.GetInt("UserID");
                            //申请人  
                            flow.Status = 1;//已通过
                            flow.Remarks = "团队端收款" + (flow.Currency == 1 ? "RMB" : "$") + "[" + flow.Amount + "]";
                            flow.CreateTime = DateTime.Now;
                            flow.ApplyID = param.GetInt("UserID");
                            //flow.Abstract = 1;//摘要 1充值 2消费 3退款 4提现
                            flow.Type = 1;//交易类型 收入 1 出货款 2 退回供应商 支出 3 自留现货 4到货 
                            trans_payOrders.Add(flow);
                            //客户的余额增加 
                            #endregion
                            #endregion
                            try
                            {
                                //2.余额支付事务
                                trans_payOrders.CommitTransaction(); //提交事务
                                return CommonLog.MsgSuccessInfo("收款成功");
                            }
                            catch (Exception)
                            {
                                trans_payOrders.RollBackTransaction();//回滚事务
                                return CommonLog.MsgErrorInfo("收款失败");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,没任何订单");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败，程序错误");
            }
        }

        /// <summary>
        /// 付款
        /// </summary>
        /// <param name="receiptOrdersParam"></param>
        /// <returns></returns>
        public string ReceiptOrders(string receiptOrdersParam)
        {
            logParam = receiptOrdersParam;

            HashParam param = Json.Deserialize<HashParam>(receiptOrdersParam);
            string tttagKey = CommonUrl.getURL(param, receiptOrdersParam);
            param["OrderIds"] = param["OrderIDs"].ToString().Split(',');

            try
            {
                if (param.GetString("OrderIDs") != null && param.GetString("OrderIDs") != "")
                {
                    using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                    {
                        IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderList", param);//OrderIDs
                        OrderList = OrderList.OrderByDescending(t => t.PaymentStatus).ToList();//从高到低排序 1已支付 0未支付 为了及时发现已支付的
                        if (OrderList != null && OrderList.Count > 0)
                        {
                            decimal? totalRMB = 0, totalUSD = 0;
                            BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("BankID"));
                            if (_bank != null)
                            {
                                //更新账户和多个订单
                                #region
                                for (int i = 0; i < OrderList.Count; i++)
                                {
                                    //未支付0 已支付1 未付清2
                                    if (OrderList[i].PaymentStatus != 1)
                                    {
                                        //人民币账户
                                        if (_bank.Currency == 1)
                                        {
                                            if (OrderList[i].PurchaseUSD != null)
                                            {
                                                OrderList[i].PurchaseRMB = OrderList[i].PurchaseUSD * OrderList[i].PurchaseExchangerate;
                                            }
                                            //全部付
                                            #region
                                            //客户当前余额大于当前订单应付金额（每个订单先四舍五入后再扣款10-11）
                                            //未付0
                                            if (OrderList[i].PaymentStatus == 0)
                                            {
                                                //现货订单付款
                                                if (OrderList[i].Supplier == tttagKey && _bank.BankBalance >= Math.Round(Convert.ToDecimal(OrderList[i].BuyRMBPrice)) && _bank.BankBalance > 0)
                                                {
                                                    _bank.BankBalance = _bank.BankBalance + (-(Math.Round(Convert.ToDecimal(OrderList[i].BuyRMBPrice))));//加减数
                                                    OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                    OrderList[i].PaymentBankID = _bank.BankID.Value;
                                                    OrderList[i].PaymentTime = DateTime.Now;//支付时间
                                                    totalRMB += OrderList[i].BuyRMBPrice;
                                                }//订单付款
                                                else if (_bank.BankBalance >= Math.Round(Convert.ToDecimal(OrderList[i].PurchaseRMB)) && _bank.BankBalance > 0) //Round 四舍六入五取偶
                                                {
                                                    _bank.BankBalance = _bank.BankBalance + (-(Math.Round(Convert.ToDecimal(OrderList[i].PurchaseRMB))));//加减数
                                                    OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                    OrderList[i].PaymentBankID = _bank.BankID.Value;
                                                    OrderList[i].PaymentTime = DateTime.Now;//支付时间
                                                    totalRMB += OrderList[i].PurchaseRMB;
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("【全部付】账户余额不足");
                                                }
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("【全部付】请使用'部分付'支付'未清'订单");
                                            }
                                            #endregion 
                                        }
                                        else if (_bank.Currency == 2)
                                        {
                                            //全部付
                                            #region
                                            //美金账户
                                            //客户当前余额大于当前订单应付金额（每个订单先四舍五入后再扣款10-11）
                                            //未付0
                                            if (OrderList[i].PaymentStatus == 0)
                                            {
                                                //现货订单付款
                                                if (OrderList[i].Supplier == tttagKey && _bank.BankBalance >= (Convert.ToDecimal(OrderList[i].BuyUSDPrice)) && _bank.BankBalance > 0)
                                                {
                                                    _bank.BankBalance = _bank.BankBalance + (-((Convert.ToDecimal(OrderList[i].BuyUSDPrice))));//加减数
                                                    OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                    OrderList[i].PaymentBankID = _bank.BankID.Value;
                                                    OrderList[i].PaymentTime = DateTime.Now;//支付时间
                                                    totalRMB += OrderList[i].BuyUSDPrice;
                                                }//订单付款
                                                else if (_bank.BankBalance >= (Convert.ToDecimal(OrderList[i].PurchaseUSD)) && _bank.BankBalance > 0) //Round 四舍六入五取偶
                                                {
                                                    _bank.BankBalance = _bank.BankBalance + (-((Convert.ToDecimal(OrderList[i].PurchaseUSD))));//加减数 
                                                    OrderList[i].PaymentStatus = 1;//支付状态(1已支付 0 未支付)
                                                    OrderList[i].PaymentBankID = _bank.BankID.Value;
                                                    OrderList[i].PaymentTime = DateTime.Now;//支付时间
                                                    totalUSD += OrderList[i].PurchaseUSD;
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("【全部付】账户余额不足");
                                                }
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("【全部付】请使用'部分付'支付'未清'订单");
                                            }
                                            #endregion
                                        }
                                        #region
                                        int editBalanceResult = trans_payOrders.Edit(_bank);//更新客户余额事务 要用Edit 12-10
                                        if (editBalanceResult > 0)
                                        {
                                            //更新订单
                                            #region  
                                            int editOrderResult = trans_payOrders.Edit(OrderList[i]);//更新订单支付状态
                                            if (editOrderResult > 0)
                                            {
                                                //继续
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("订单不存在");
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("账户不存在");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        //已支付1订单
                                        return CommonLog.MsgErrorInfo("失败,订单已付款");
                                    }
                                }
                                #endregion
                                //生成流水
                                #region
                                FlowInfo _flow = new FlowInfo();
                                _flow.CreateTime = DateTime.Now;
                                _flow.UpdateTime = DateTime.Now;
                                if (_bank.Currency == 1)
                                {
                                    _flow.Amount = totalRMB;
                                }
                                else if (_bank.Currency == 2)
                                {
                                    _flow.Amount = totalUSD;
                                }
                                _flow.Balance = _bank.BankBalance;
                                _flow.Currency = _bank.Currency;
                                _flow.Account = _bank.BankID;
                                _flow.Type = 2;
                                _flow.Abstract = 0;//0订单付款
                                _flow.Purpose = 1;//1裸钻
                                _flow.OrderIDs = param.GetString("OrderIDs");
                                _flow.ApplyID = param.GetInt("UserID");
                                _flow.ReviewID = param.GetInt("UserID");
                                _flow.Remarks = "团队端付款" + (_flow.Currency == 1 ? "RMB" : "$") + "[" + _flow.Amount + "]";
                                _flow.ArrivalTime = DateTime.Now;
                                _flow.Status = 1;
                                int addFlowResult = trans_payOrders.Add(_flow);
                                if (addFlowResult > 0)
                                {
                                    //继续
                                }
                                else
                                {
                                    //跳出
                                    return CommonLog.MsgErrorInfo("生成流水失败");
                                }
                                #endregion
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("账户不存在,检查账户标识");
                            }
                            try
                            {
                                trans_payOrders.CommitTransaction(); //提交
                                return CommonLog.MsgSuccessInfo("付款成功");
                            }
                            catch (Exception ex)
                            {
                                GetMethodInfoAndWriteLogs(ex);
                                trans_payOrders.RollBackTransaction();//回滚
                                return CommonLog.MsgErrorInfo("付款失败,请重试");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("失败,没任何订单");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("失败,没选择任何订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 团队 更新所在地
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdatePlace(string strParam)
        {
            logParam = strParam;
            HashParam param = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(param, strParam);
            param["OrderIds"] = param["OrderIds"].ToString().Split(',');
            string place = param.GetString("Place");
            IList<OrderInfo> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfo>("Order.SelectOrderList", param);//OrderIDs
            using (ITransaction trans_purchaseOrders = YZ.GetTransaction(tttagKey))
            {
                for (int i = 0; i < OrderList.Count; i++)
                {
                    Inventory _inventory = Json.Deserialize<Inventory>(OrderList[i].InventoryAttribute);
                    _inventory.Place = place;
                    OrderList[i].InventoryAttribute = JsonConvert.SerializeObject(_inventory);
                    int update = trans_purchaseOrders.Edit(OrderList[i]);
                }
                trans_purchaseOrders.CommitTransaction();
                return CommonLog.MsgSuccessInfo("更新成功");
            }

        }
        /// <summary>
        /// 采购订单（处理（1下单成功，待采购）的订单到 (2采购成功，待入库)） --含事务    （改变订单状态 从1到2）
        /// </summary>
        /// <param name="purchaseOrdersParam"></param>
        /// <returns></returns>
        public string PurchaseOrder(string purchaseOrderParam)
        {
            return CRetails.PurchaseOrder(purchaseOrderParam);
        }

        /// <summary>
        /// 回库
        /// </summary>
        /// <param name="addDiaParam"></param>
        /// <returns></returns>
        public string ReStock(string addDiaParam)
        {
            //PurchaseDiscountReturn 买退点 OriginDiscountReturn 原退点
            //前台传值统一参数名 免得混乱，新增与修改
            addDiaParam = addDiaParam.Replace("SourceDiscountReturn", "OriginDiscountReturn").Replace("SourceDolarPerGrain", "OriginUSDPerGrain").Replace("SourceDolarPerCarat", "OriginUSDPerCarat").Replace("BuyUSDPrice", "PurchaseUSDPerGrain").Replace("BuyRMBPrice", "PurchaseRMB ").Replace("PurchaseUserID", "PurchaseAgent").Replace("PurchaseExchangerate", "PurchaseExchange");

            logParam = addDiaParam;
            var _beforeParam = JsonConvert.DeserializeObject<HashParam>(addDiaParam);
            string tttagKey = CommonUrl.getURL(_beforeParam, addDiaParam);

            try
            {
                //给中心发消息删除订单 2017-03-23
                #region
                long? _orderID = _beforeParam.GetInt("OrderID");
                if (_beforeParam.GetString("OrderID") != "")
                {
                    OrderInfo _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", _orderID);
                    string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, _order.GoodsTypeID);
                    var result = "";
                    #region 裸钻
                    if (_order.GoodsTypeID == GoodsType.Diamond)
                    {
                        Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(_order.InventoryAttribute);
                        if (_order.Supplier == tttagKey)
                        {
                            #region  现货删除订单
                            string[] _inventoryIDs = _order.InventoryID.ToString().TrimEnd(',').Split(',');
                            int[] InventoryIDs = new int[_inventoryIDs.Length];
                            for (int i = 0; i < _inventoryIDs.Length; i++)
                            {
                                InventoryIDs[i] = Convert.ToInt32(_inventoryIDs[i]);//不能为空
                            }
                            TransmissionOrderResult delOrderResult = AllPublic.OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单 
                            if (delOrderResult.Result)
                            {
                                #region  更新订单状态
                                if (_order != null)
                                {
                                    _order.Online = 1;//1已回库 空 待回库
                                    _order.ModifyTime = DateTime.Now;
                                    using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                    {
                                        int editOrderResult = trans_editOrder.Edit(_order);
                                        if (editOrderResult > 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("更新订单失败");
                                        }
                                        try
                                        {
                                            trans_editOrder.CommitTransaction(); //提交事务
                                                                                 //{CertType: ["GIA"], IsFancy: "0", IsStock: 1, OnShelves: 1, limit: 500, useDict: true} 得到证书信息再去查询有没有这个现货
                                            Dictionary<string, object> certDisc = new Dictionary<string, object>();

                                            certDisc.Add("CertType", new string[1] { _inventory.CertType });
                                            certDisc.Add("CertNo", new string[1] { _inventory.CertNo });
                                            certDisc.Add("IsFancy", _inventory.IsFancy);
                                            certDisc.Add("IsStock", 1);
                                            certDisc.Add("useDict", "true");
                                            var _result = GetInventoryInfos(JsonConvert.SerializeObject(certDisc));
                                            if (_result.Contains("获取库存成功") && _result.Contains("SourceDiscountReturn")) //防止中心返回成功但是是[] 没有数据
                                            {
                                                return CommonLog.MsgSuccessInfo("回库成功");
                                            }
                                            else
                                            {
                                                //如果数据中心现货没有这个删除的订单
                                                //继续走新增
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            GetMethodInfoAndWriteLogs(ex);
                                            trans_editOrder.RollBackTransaction();//回滚事务
                                            return CommonLog.MsgErrorInfo("失败,请重试");
                                        }
                                    }
                                }
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {
                            //非现货
                            HashParam hsParam = Json.Deserialize<HashParam>(_order.InventoryAttribute);
                            //不需要指定的字段：ID, InsertTime, UpdateTime, SN, IsFancy, Supplier
                            hsParam.Remove("ID");
                            hsParam.Remove("InsertTime");
                            hsParam.Remove("UpdateTime");
                            hsParam.Remove("SN");
                            hsParam.Remove("IsFancy");
                            hsParam.Remove("Supplier");
                            hsParam.Remove("ShortName");
                            hsParam["PurchaseExchange"] = _beforeParam.GetString("PurchaseExchange");
                            hsParam["PurchaseDiscountReturn"] = _beforeParam.GetString("PurchaseReturn");
                            hsParam["PurchaseRMB"] = _beforeParam.GetString("PurchaseRMB");
                            hsParam["PurchaseSupplier"] = _beforeParam.GetString("BuyPurchaseSupplier");
                            hsParam["PurchaseTime"] = _beforeParam.GetString("BuyPurchaseTime");
                            hsParam["ArrivalTime"] = _beforeParam.GetString("ArrivalTime");
                            hsParam["ReceiptStatus"] = _beforeParam.GetString("ReceiptStatus");
                            hsParam["ShipTime"] = _beforeParam.GetString("ShipTime");
                            string ShipTime = hsParam.GetString("ShipTime");
                            if (ShipTime == "")
                                hsParam.Remove("ShipTime");
                            else
                            {
                                if (Convert.ToDateTime(ShipTime).Year < 1971)
                                {
                                    hsParam.Remove("ShipTime");
                                }
                            }
                            string PurchaseTime = hsParam.GetString("PurchaseTime");
                            if (PurchaseTime == "")
                                hsParam.Remove("PurchaseTime");
                            else
                            {
                                if (Convert.ToDateTime(PurchaseTime).Year < 1971)
                                {
                                    hsParam.Remove("PurchaseTime");
                                }
                            }
                            string ArrivalTime = hsParam.GetString("ArrivalTime");
                            if (ArrivalTime == "")
                                hsParam.Remove("ArrivalTime");
                            else
                            {
                                if (Convert.ToDateTime(ArrivalTime).Year < 1971)
                                {
                                    hsParam.Remove("ArrivalTime");
                                }
                            }
                            UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);
                            if (userinfo != null)
                                hsParam["PurchaseAgent"] = userinfo.UserName;
                            #region
                            Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(hsParam));
                            object[] str = { param };
                            Dictionary<string, object> tempParam = new Dictionary<string, object>();//组装 
                            tempParam.Add("rows", str);
                            string lastParam = JsonConvert.SerializeObject(tempParam);//把{} 组装成 { "rows":[{},{}]}
                            #endregion
                            TransmissionOrderResult tor = new TransmissionOrderResult();
                            int totalSeconds;
                            string signStr;
                            var guid = Guid.NewGuid().ToString();
                            var objParams = JsonConvert.DeserializeObject<JObject>(lastParam);
                            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                            MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                            //获取数据仓库库存（远程） 多个ID获取多条库存
                            result =
                                 MyHttpRequest.PostJSONByRequestParam(
                                    new RequestInfo() { RequestJson = lastParam, RequestUrl = GlobalConfig.TransmissionUpStockURL }     //添加库存  lastParam 为 { "rows":[{},{}]}
                                     , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST
                            );
                            if (result.Contains(".py"))
                            {
                                result = CommonLog.MsgErrorInfo("远程服务错误");
                            }
                            else if (result.Contains("true"))
                            {
                                //删除数据中心订单
                                //{\"count\": 1, \"ids_insert\": [], \"ids\": [12076947], \"ids_update\": [12076947], \"result\": true, \"count_update\": 1, \"count_insert\": 0}
                                string pattern = @"\d{6,12}";
                                bool b = false;
                                foreach (Match match in Regex.Matches(result, pattern))
                                {
                                    b = true;
                                    int[] InventoryIDs = new int[1];
                                    InventoryIDs[0] = Convert.ToInt32(match.Value);
                                    TransmissionOrderResult delOrderResult = AllPublic.OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单 
                                    break;
                                }
                                if (!b)
                                {
                                    //记录result 的值，看看为什么无法匹配上述正则 
                                    GetMethodInfoAndWriteLogs(null, string.Format("删除对应的其它供应商回库的货失败，result:{0}", result));
                                }

                                //更新回库状态Online为1已上线
                                #region 
                                if (_order != null)
                                {
                                    _order.Online = 1;//1已回库 空 待回库
                                    _order.ModifyTime = DateTime.Now;
                                    using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                    {
                                        int editOrderResult = trans_editOrder.Edit(_order);
                                        if (editOrderResult > 0)
                                        {
                                            //继续
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("更新订单失败");
                                        }
                                        try
                                        {
                                            trans_editOrder.CommitTransaction(); //提交事务
                                        }
                                        catch (Exception ex)
                                        {
                                            GetMethodInfoAndWriteLogs(ex);
                                            trans_editOrder.RollBackTransaction();//回滚事务
                                            return CommonLog.MsgErrorInfo("失败,请重试");
                                        }
                                    }
                                }
                                #endregion
                            }
                            //{"count": 1, "ids_insert": [], "ids": [5396789], "ids_update": [5396789], "result": true, "count_update": 1, "count_insert": 0}
                            return result;

                        }
                    }
                    #endregion
                    #region 成品
                    else if (_order.GoodsTypeID == GoodsType.Ring)
                    {
                        if (!_beforeParam.ContainsKey("StyleNo"))
                        {
                            return CommonLog.MsgErrorInfo("没有款号");
                        }
                        else if (string.IsNullOrEmpty(_beforeParam["StyleNo"].ToString()))
                        {
                            return CommonLog.MsgErrorInfo("款号不能为空");
                        }
                        //1 判断是否现货
                        if (_order.Supplier == tttagKey)
                        {
                            //查询数据中心库存，更新重量
                            var productIdsStr = CRetails.GetIdsStrParamByIds(new int[] { _order.InventoryID ?? 0 }); //加入 useDict：true等元素 
                            string responseJson = CRetails.AllProduct(tttagKey, productIdsStr, filterUrl);
                            Products<Ring> list = JsonConvert.DeserializeObject<Products<Ring>>(responseJson);
                            if (list.Rows.Count == 1)//查询到数据中心已经存在
                            {
                                Ring newParcels = list.Rows[0];
                                //更新货品数量即可
                                HashParam addParam = new HashParam();
                                addParam.Add("IsStock", "1");// 1 现货
                                addParam.Add("StyleNo", _beforeParam.GetString("StyleNo"));
                                //新增参数
                                addParam.Add("ReceiptStatus", "0");//付款状态 
                                addParam.Add("PurchaseRMB", _order.BuyRMBPrice.ToString());
                                addParam.Add("PurchaseUSD", _order.BuyUSDPrice.ToString());
                                addParam.Add("PurchaseExchange", _order.PurchaseExchangerate.ToString());
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam.Add("PurchaseAgent", userinfo.UserName);
                                if (_order.BuyPurchaseTime != null && _order.BuyPurchaseTime.Value.Year > 1970)
                                {
                                    addParam.Add("PurchaseTime", _order.BuyPurchaseTime.Value.ToString("yyyy-MM-dd"));
                                }
                                if (_order.ShipTime != null && _order.ShipTime.Value.Year > 1970)
                                {
                                    addParam.Add("ShipTime", _order.ShipTime.Value.ToString("yyyy-MM-dd"));
                                }
                                if (_order.ArrivalTime != null && Convert.ToDateTime(_order.ArrivalTime).Year > 1970)
                                {
                                    addParam.Add("ArrivalTime", _order.ArrivalTime);
                                }
                                var attr = JsonConvert.SerializeObject(addParam);
                                result = CRetails.AllProduct(tttagKey, attr, string.Format(GlobalConfig.TransmissionInlaysOprateUrl, _order.InventoryID), "put");
                            }
                            else if (list.Rows.Count == 0)
                            {
                                //新增 不需要指定的字段：ID, InsertTime, UpdateTime, SN, IsFancy, Supplier
                                HashParam addParam = Json.Deserialize<HashParam>(_order.InventoryAttribute);
                                addParam.Remove("ID");
                                addParam.Remove("CreateTime");
                                addParam.Remove("InsertTime");
                                addParam.Remove("UpdateTime");
                                addParam.Remove("Supplier");
                                addParam["IsStock"] = "1";// 1 现货
                                addParam["StyleNo"] = _beforeParam.GetString("StyleNo");
                                addParam["Price"] = addParam["Price"].ToString();
                                addParam["CostPrice"] = addParam["CostPrice"].ToString();
                                addParam["Weight"] = addParam["Weight"].ToString();
                                addParam["SideWeight"] = addParam["SideWeight"].ToString();
                                addParam["MainWeight"] = addParam["MainWeight"].ToString();
                                //新增参数
                                addParam["ReceiptStatus"] = "0";//付款状态
                                addParam["PurchaseRMB"] = _order.BuyRMBPrice.ToString();
                                addParam["PurchaseUSD"] = _order.BuyUSDPrice.ToString();
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam["PurchaseAgent"] = userinfo.UserName;
                                else
                                    addParam.Remove("PurchaseAgent");
                                if (_order.BuyPurchaseTime != null && _order.BuyPurchaseTime.Value.Year < 1971)
                                    addParam.Remove("PurchaseTime");
                                else
                                {
                                    addParam["PurchaseTime"] = _order.BuyPurchaseTime.Value.ToString("yyyy-MM-dd");
                                }
                                if (_order.ShipTime != null && _order.ShipTime.Value.Year < 1971)
                                    addParam.Remove("ShipTime");
                                else
                                {
                                    addParam["ShipTime"] = _order.ShipTime.Value.ToString("yyyy-MM-dd");
                                }
                                if (_order.ArrivalTime != null && Convert.ToDateTime(_order.ArrivalTime).Year < 1971)
                                    addParam.Remove("ArrivalTime");
                                else
                                {
                                    addParam["ArrivalTime"] = _order.ArrivalTime;
                                }
                                var addParamStr = JsonConvert.SerializeObject(addParam);
                                //新增
                                filterUrl = GoodsType.GetGoodsUrlByTypId("", _order.GoodsTypeID);
                                result = CRetails.AllProduct(tttagKey, addParamStr, GlobalConfig.TransmissionInlaysOprateUrl, "post");
                            }
                        }
                        else
                        {
                            //订单的属性
                            Ring parcels = JsonConvert.DeserializeObject<Ring>(_order.InventoryAttribute);
                            HashParam newParam = new HashParam();
                            newParam.Add("Supplier", tttagKey);//自己的货
                            newParam.Add("OriginSN", parcels.OriginSN);
                            newParam.Add("useDict", true);
                            string getProductParam = JsonConvert.SerializeObject(newParam);
                            result = CRetails.AllProduct(tttagKey, getProductParam, filterUrl, "post");
                            Products<Ring> list = JsonConvert.DeserializeObject<Products<Ring>>(result);
                            if (list.Rows.Count == 1)//查询到数据中心已经存在
                            {
                                Ring newParcels = list.Rows[0];
                                //更新货品数量即可
                                HashParam addParam = new HashParam();
                                addParam.Add("IsStock", "1");// 1 现货  
                                                             //新增字段 
                                addParam.Add("ReceiptStatus", "0");
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam.Add("PurchaseAgent", userinfo.UserName);
                                var attr = JsonConvert.SerializeObject(addParam);
                                result = CRetails.AllProduct(tttagKey, attr, string.Format(GlobalConfig.TransmissionInlaysOprateUrl, newParcels.ID), "put");
                            }
                            else if (list.Rows.Count == 0)
                            {
                                //新增 不需要指定的字段：ID, InsertTime, UpdateTime, SN, IsFancy, Supplier
                                HashParam addParam = Json.Deserialize<HashParam>(_order.InventoryAttribute);
                                addParam.Remove("ID");
                                addParam.Remove("InsertTime");
                                addParam.Remove("UpdateTime");
                                addParam.Remove("Supplier");
                                addParam["IsStock"] = "1";// 1 现货
                                addParam["StyleNo"] = _beforeParam.GetString("StyleNo");
                                addParam["Price"] = addParam["Price"].ToString();
                                addParam["CostPrice"] = addParam["CostPrice"].ToString();
                                addParam["Weight"] = addParam["Weight"].ToString();
                                addParam["SideWeight"] = addParam["SideWeight"].ToString();
                                addParam["MainWeight"] = addParam["MainWeight"].ToString();
                                //新增字段
                                addParam.Remove("PurchaseTime");
                                addParam.Remove("PurchaseSupplier");
                                addParam.Remove("PurchaseUSD");
                                addParam.Remove("PurchaseRMB");
                                addParam["ReceiptStatus"] = "0";
                                addParam.Remove("ShipTime");
                                addParam.Remove("ArrivalTime");
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam["PurchaseAgent"] = userinfo.UserName;
                                else
                                    addParam.Remove("PurchaseAgent");
                                var addParamStr = JsonConvert.SerializeObject(addParam);
                                //新增
                                filterUrl = GoodsType.GetGoodsUrlByTypId("", _order.GoodsTypeID);
                                result = CRetails.AllProduct(tttagKey, addParamStr, GlobalConfig.TransmissionInlaysOprateUrl, "post");
                            }
                        }

                        if (result == "{\"result\": true}")
                        {
                            #region  更新订单状态
                            if (_order != null)
                            {
                                _order.Online = 1;//1已回库 空 待回库
                                _order.ModifyTime = DateTime.Now;
                                using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                {
                                    int editOrderResult = trans_editOrder.Edit(_order);
                                    if (editOrderResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("更新订单失败");
                                    }
                                    try
                                    {
                                        trans_editOrder.CommitTransaction(); //提交事务 
                                        return CommonLog.MsgSuccessInfo("回库成功");
                                    }
                                    catch (Exception ex)
                                    {
                                        GetMethodInfoAndWriteLogs(ex);
                                        trans_editOrder.RollBackTransaction();//回滚事务
                                        return CommonLog.MsgErrorInfo("失败,请重试");
                                    }
                                }
                            }
                            #endregion 
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("回库失败");
                        }
                    }
                    #endregion
                    #region 空托
                    else if (_order.GoodsTypeID == GoodsType.InlaySettings)
                    {
                        if (!_beforeParam.ContainsKey("StyleNo"))
                        {
                            return CommonLog.MsgErrorInfo("没有款号");
                        }
                        else if (string.IsNullOrEmpty(_beforeParam["StyleNo"].ToString()))
                        {
                            return CommonLog.MsgErrorInfo("款号不能为空");
                        }
                        //1 判断是否现货
                        if (_order.Supplier == tttagKey)
                        {
                            //查询数据中心库存，更新重量
                            var productIdsStr = CRetails.GetIdsStrParamByIds(new int[] { _order.InventoryID ?? 0 }); //加入 useDict：true等元素 
                            string responseJson = CRetails.AllProduct(tttagKey, productIdsStr, filterUrl);
                            Products<InlaySettings> list = JsonConvert.DeserializeObject<Products<InlaySettings>>(responseJson);
                            if (list.Rows.Count == 1)//查询到数据中心已经存在
                            {
                                InlaySettings newInlaySettings = list.Rows[0];
                                //更新货品数量即可
                                HashParam addParam = new HashParam();
                                addParam.Add("IsStock", "1");// 1 现货
                                addParam.Add("StyleNo", _beforeParam.GetString("StyleNo"));
                                //新增参数
                                addParam.Add("ReceiptStatus", "0");//付款状态 
                                addParam.Add("PurchaseRMB", _order.BuyRMBPrice.ToString());
                                addParam.Add("PurchaseUSD", _order.BuyUSDPrice.ToString());
                                addParam.Add("PurchaseExchange", _order.PurchaseExchangerate.ToString());
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam.Add("PurchaseAgent", userinfo.UserName);
                                if (_order.BuyPurchaseTime != null && _order.BuyPurchaseTime.Value.Year > 1970)
                                {
                                    addParam.Add("PurchaseTime", _order.BuyPurchaseTime.Value.ToString("yyyy-MM-dd"));
                                }
                                if (_order.ShipTime != null && _order.ShipTime.Value.Year > 1970)
                                {
                                    addParam.Add("ShipTime", _order.ShipTime.Value.ToString("yyyy-MM-dd"));
                                }
                                if (_order.ArrivalTime != null && Convert.ToDateTime(_order.ArrivalTime).Year > 1970)
                                {
                                    addParam.Add("ArrivalTime", _order.ArrivalTime);
                                }
                                var attr = JsonConvert.SerializeObject(addParam);
                                result = CRetails.AllProduct(tttagKey, attr, string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, _order.InventoryID), "put");
                            }
                            else if (list.Rows.Count == 0)
                            {
                                //新增 不需要指定的字段：ID, InsertTime, UpdateTime, SN, IsFancy, Supplier
                                HashParam addParam = Json.Deserialize<HashParam>(_order.InventoryAttribute);
                                addParam.Remove("ID");
                                addParam.Remove("CreateTime");
                                addParam.Remove("InsertTime");
                                addParam.Remove("UpdateTime");
                                addParam.Remove("Supplier");
                                addParam.Remove("GoldPrice");
                                addParam.Remove("Price");
                                addParam.Remove("CustomerGoldPrice");
                                addParam.Remove("CustomerSideLaborFee");
                                addParam.Remove("CustomerLaborFee");
                                addParam.Remove("CustomerWastage");
                                addParam.Remove("CustomerSidePrice");
                                addParam.Remove("CustomerInsurance");
                                addParam["IsStock"] = "1";// 1 现货
                                addParam["StyleNo"] = _beforeParam.GetString("StyleNo");
                                addParam["OriginSN"] = _beforeParam.GetString("OriginSN");
                                addParam["Technics"] = _beforeParam.GetString("Technics");
                                addParam["Type"] = _beforeParam.GetString("Type");
                                addParam["Series"] = _beforeParam.GetString("Series");
                                addParam["Material"] = _beforeParam.GetString("Material");
                                addParam["MainShape"] = _beforeParam.GetString("MainShape");
                                addParam["MainWeight"] = _beforeParam.GetString("MainWeight");
                                addParam["SideWeight"] = _beforeParam.GetString("SideWeight");
                                addParam["SideNum"] = _beforeParam.GetString("SideNum");
                                addParam["BuyGoldPrice"] = _beforeParam.GetString("BuyGoldPrice");
                                addParam["BuyWastage"] = _beforeParam.GetString("BuyWastage");
                                addParam["BuySidePrice"] = _beforeParam.GetString("BuySidePrice");
                                addParam["BuyLaborFee"] = _beforeParam.GetString("BuyLaborFee");
                                addParam["NetGoldWeight"] = _beforeParam.GetString("NetGoldWeight");
                                addParam["SidePrice"] = _beforeParam.GetString("SidePrice");
                                addParam["TotalWeight"] = _beforeParam.GetString("TotalWeight");
                                addParam["LaborFee"] = _beforeParam.GetString("LaborFee");
                                addParam["Wastage"] = _beforeParam.GetString("Wastage");
                                addParam["Insurance"] = _beforeParam.GetString("Insurance");
                                addParam["Measurement"] = _beforeParam.GetString("Measurement");
                                addParam["Manufactor"] = _beforeParam.GetString("Manufactor");
                                addParam["Country"] = _beforeParam.GetString("Country");
                                addParam["State"] = _beforeParam.GetString("State");
                                addParam["Remark"] = _beforeParam.GetString("Remarks");
                                //新增参数
                                addParam["PurchaseExchange"] = addParam["PurchaseExchange"].ToString();
                                addParam["SideLaborFee"] = addParam["SideLaborFee"].ToString();
                                addParam["ReceiptStatus"] = "0";//付款状态
                                addParam["PurchaseRMB"] = _order.BuyRMBPrice.ToString();
                                addParam["PurchaseUSD"] = _order.BuyUSDPrice.ToString();
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam["PurchaseAgent"] = userinfo.UserName;
                                else
                                    addParam.Remove("PurchaseAgent");
                                if (_order.BuyPurchaseTime != null && _order.BuyPurchaseTime.Value.Year < 1971)
                                    addParam.Remove("PurchaseTime");
                                else
                                {
                                    addParam["PurchaseTime"] = _order.BuyPurchaseTime.Value.ToString("yyyy-MM-dd");
                                }
                                if (_order.ShipTime != null && _order.ShipTime.Value.Year < 1971)
                                    addParam.Remove("ShipTime");
                                else
                                {
                                    addParam["ShipTime"] = _order.ShipTime.Value.ToString("yyyy-MM-dd");
                                }
                                if (_order.ArrivalTime != null && Convert.ToDateTime(_order.ArrivalTime).Year < 1971)
                                    addParam.Remove("ArrivalTime");
                                else
                                {
                                    addParam["ArrivalTime"] = _order.ArrivalTime;
                                }
                                var addParamStr = JsonConvert.SerializeObject(addParam);
                                //新增
                                filterUrl = GoodsType.GetGoodsUrlByTypId("", _order.GoodsTypeID);
                                result = CRetails.AllProduct(tttagKey, addParamStr, GlobalConfig.TransmissionInlaySettingsOprateUrl, "post");
                            }
                        }
                        else
                        {
                            //订单的属性
                            InlaySettings inlaySettings = JsonConvert.DeserializeObject<InlaySettings>(_order.InventoryAttribute);
                            HashParam newParam = new HashParam();
                            newParam.Add("Supplier", tttagKey);//自己的货
                            newParam.Add("OriginSN", inlaySettings.OriginSN);
                            newParam.Add("useDict", true);
                            string getProductParam = JsonConvert.SerializeObject(newParam);
                            result = CRetails.AllProduct(tttagKey, getProductParam, filterUrl, "post");
                            Products<InlaySettings> list = JsonConvert.DeserializeObject<Products<InlaySettings>>(result);
                            if (list.Rows.Count == 1)//查询到数据中心已经存在
                            {
                                InlaySettings newInlaySettings = list.Rows[0];
                                //更新货品数量即可
                                HashParam addParam = new HashParam();
                                addParam.Add("IsStock", "1");// 1 现货  
                                                             //新增字段 
                                addParam.Add("ReceiptStatus", "0");
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam.Add("PurchaseAgent", userinfo.UserName);
                                var attr = JsonConvert.SerializeObject(addParam);
                                result = CRetails.AllProduct(tttagKey, attr, string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, newInlaySettings.ID), "put");
                            }
                            else if (list.Rows.Count == 0)
                            {
                                //新增 不需要指定的字段：ID, InsertTime, UpdateTime, SN, IsFancy, Supplier
                                HashParam addParam = Json.Deserialize<HashParam>(_order.InventoryAttribute);
                                addParam.Remove("ID");
                                addParam.Remove("InsertTime");
                                addParam.Remove("UpdateTime");
                                addParam.Remove("Supplier");
                                addParam.Remove("GoldPrice");
                                addParam.Remove("Price");
                                addParam.Remove("CustomerGoldPrice");
                                addParam.Remove("CustomerSideLaborFee");
                                addParam.Remove("CustomerLaborFee");
                                addParam.Remove("CustomerWastage");
                                addParam.Remove("CustomerSidePrice");
                                addParam.Remove("CustomerInsurance");
                                addParam["IsStock"] = "1";// 1 现货
                                addParam["StyleNo"] = _beforeParam.GetString("StyleNo");
                                addParam["OriginSN"] = _beforeParam.GetString("OriginSN");
                                addParam["Technics"] = _beforeParam.GetString("Technics");
                                addParam["Type"] = _beforeParam.GetString("Type");
                                addParam["Series"] = _beforeParam.GetString("Series");
                                addParam["Material"] = _beforeParam.GetString("Material");
                                addParam["MainShape"] = _beforeParam.GetString("MainShape");
                                addParam["MainWeight"] = _beforeParam.GetString("MainWeight");
                                addParam["SideWeight"] = _beforeParam.GetString("SideWeight");
                                addParam["SideNum"] = _beforeParam.GetString("SideNum");
                                addParam["BuyGoldPrice"] = _beforeParam.GetString("BuyGoldPrice");
                                addParam["BuyWastage"] = _beforeParam.GetString("BuyWastage");
                                addParam["BuySidePrice"] = _beforeParam.GetString("BuySidePrice");
                                addParam["BuyLaborFee"] = _beforeParam.GetString("BuyLaborFee");
                                addParam["NetGoldWeight"] = _beforeParam.GetString("NetGoldWeight");
                                addParam["SidePrice"] = _beforeParam.GetString("SidePrice");
                                addParam["TotalWeight"] = _beforeParam.GetString("TotalWeight");
                                addParam["LaborFee"] = _beforeParam.GetString("LaborFee");
                                addParam["Wastage"] = _beforeParam.GetString("Wastage");
                                addParam["Insurance"] = _beforeParam.GetString("Insurance");
                                addParam["Measurement"] = _beforeParam.GetString("Measurement");
                                addParam["Manufactor"] = _beforeParam.GetString("Manufactor");
                                addParam["Country"] = _beforeParam.GetString("Country");
                                addParam["State"] = _beforeParam.GetString("State");
                                addParam["Remark"] = _beforeParam.GetString("Remarks");
                                //新增字段
                                addParam["SideLaborFee"] = addParam["SideLaborFee"].ToString();
                                addParam.Remove("PurchaseTime");
                                addParam.Remove("PurchaseSupplier");
                                addParam.Remove("PurchaseUSD");
                                addParam.Remove("PurchaseRMB");
                                addParam["ReceiptStatus"] = "0";
                                addParam.Remove("ShipTime");
                                addParam.Remove("ArrivalTime");
                                UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", _order.PurchaseUserID);//采购
                                if (userinfo != null)
                                    addParam["PurchaseAgent"] = userinfo.UserName;
                                else
                                    addParam.Remove("PurchaseAgent");
                                var addParamStr = JsonConvert.SerializeObject(addParam);
                                //新增
                                filterUrl = GoodsType.GetGoodsUrlByTypId("", _order.GoodsTypeID);
                                result = CRetails.AllProduct(tttagKey, addParamStr, GlobalConfig.TransmissionInlaySettingsOprateUrl, "post");
                            }
                        }
                        if (result == "{\"result\": true}")
                        {
                            #region  更新订单状态
                            if (_order != null)
                            {
                                _order.Online = 1;//1已回库 空 待回库
                                _order.ModifyTime = DateTime.Now;
                                using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                {
                                    int editOrderResult = trans_editOrder.Edit(_order);
                                    if (editOrderResult > 0)
                                    {
                                        //继续
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("更新订单失败");
                                    }
                                    try
                                    {
                                        trans_editOrder.CommitTransaction(); //提交事务 
                                        return CommonLog.MsgSuccessInfo("回库成功");
                                    }
                                    catch (Exception ex)
                                    {
                                        GetMethodInfoAndWriteLogs(ex);
                                        trans_editOrder.RollBackTransaction();//回滚事务
                                        return CommonLog.MsgErrorInfo("失败,请重试");
                                    }
                                }
                            }
                            #endregion 
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("回库失败");
                        }
                    }
                    #endregion
                }
                #endregion 
                return "";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }


        /// <summary>
        /// 裸钻订单结算(团队) 11-2   eegia 计算方法 其他需采取定制
        /// </summary>
        /// <param name="getOrdersParam"></param>
        /// <returns></returns>
        public string SettleOrders(string settleOrdersParam)
        {
            logParam = settleOrdersParam;
            //CustomerID、UserID            
            //PageParamOfOrder param = Json.Deserialize<PageParamOfOrder>(settleOrdersParam);
            HashParam param = Json.Deserialize<HashParam>(settleOrdersParam);
            string tttagKey = CommonUrl.getURL(param, settleOrdersParam);
            try
            {
                IList<OrderInfoResult> _ordersInfo = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.GetTeamOrdersList", param);//含数据库字段排序param, param.PageSize, param.PageIndex
                if (_ordersInfo != null && _ordersInfo.Count > 0)
                {
                    //计算利润提成等
                    #region
                    foreach (var item in _ordersInfo)
                    {
                        //计算回款天数
                        //当订单已支付，回款天数 = 支付日期 - 出货日期或到货日期  (固定) //当订单未支付，回款天数 = 当前日期 - 出货日期或到货日期  （灵活）
                        if (item.PaymentStatus == 1)
                        {
                            if (item.PaymentTime != null)
                            {
                                //已出货
                                if (item.ShipTime != null)
                                {
                                    TimeSpan ts = Convert.ToDateTime(item.PaymentTime) - Convert.ToDateTime(item.ShipTime);   //DateTime.Now - item.ShipTime;//回款（天） = 当前日期 - 出货日期
                                    item.PaybackPeriods = ts.TotalDays; //TotalDays                            
                                }
                                else if (item.ArrivalTime != null)
                                {
                                    //待出货
                                    TimeSpan ts = Convert.ToDateTime(item.PaymentTime) - Convert.ToDateTime(item.ArrivalTime); //DateTime.Now - item.ArrivalTime;//回款（天） = 当前日期 - 到货日期
                                    item.PaybackPeriods = ts.TotalDays; //TotalDays
                                }
                            }
                        }
                        else
                        {
                            if (item.ShipTime != null)
                            {
                                TimeSpan ts = DateTime.Now - Convert.ToDateTime(item.ShipTime);   //DateTime.Now - item.ShipTime;//回款（天） = 当前日期 - 出货日期
                                item.PaybackPeriods = ts.TotalDays; //TotalDays                            
                            }
                            else
                            {
                                TimeSpan ts = DateTime.Now - Convert.ToDateTime(item.ArrivalTime); //DateTime.Now - item.ArrivalTime;//回款（天） = 当前日期 - 到货日期
                                item.PaybackPeriods = ts.TotalDays; //TotalDays
                            }
                        }
                        //计算运费 必须为decimal?否则无法判断==null
                        if (item.Freight == 0)
                        {
                            //动态计算
                            if (item.Supplier.ToLower() == tttagKey)  //GlobalConfig.SelfStock 现货供应商简称 11-26
                            {
                                item.Freight = 0;  //现货运费为0
                            }
                            else
                            {
                                item.Freight = Convert.ToDecimal(item.PurchaseUSD * Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["BaseFreight"])); //运费$ = 买入$ * 0.004 (12-3启用)
                            }
                        }
                        if (item.PurchaseRMB == null)
                        {
                            item.PurchaseRMB = Convert.ToDecimal((item.PurchaseUSD + item.Freight) * item.PurchaseExchangerate); //买入RMB = (买入美金 + 运费美金)* 采购汇率 （12-3启用）
                        }
                        item.Profits = Convert.ToDecimal(item.ConfirmRMB - item.PurchaseRMB); //利润 = 卖￥ - 买 ￥ (12-3启用)
                        //计算提成
                        //已出货订单 利润 x 30% x (15 - 回款天数) 已定      5天为界限  从第6天起每天减少10%     //待出货订单 利润 x 30% x (15 - 回款天数) 已定
                        if (item.OrderStatus == 4 || item.OrderStatus == 3)
                        {
                            //如果有利润才有提成 11-11
                            if (item.Profits > 0)
                            {
                                //应得提成 2017-01-05
                                item.DesertRoyalties = item.Profits * Convert.ToDecimal(0.3);
                                if (item.PaybackPeriods > 15)
                                {
                                    item.Royalties = 0;//实得提成为0
                                }
                                else if (item.PaybackPeriods > 5)
                                {
                                    item.Royalties = item.Profits * Convert.ToDecimal(0.3) * Convert.ToDecimal(((15 - item.PaybackPeriods) * 0.1));
                                }
                                else
                                {
                                    item.Royalties = item.Profits * Convert.ToDecimal(0.3);//实得提成
                                }
                            }
                            else
                            {
                                item.Royalties = 0;//无利润 实得提成为0
                                item.DesertRoyalties = 0;//应得提成为0
                            }
                        }
                    }
                    #endregion
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_ordersInfo));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("失败");
            }
        }
        /// <summary>
        /// 批量修改裸钻价格
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public string BatchDia(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionUpBatchUrl;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT);
        }

        /// <summary>
        /// 批量修改裸钻到货时间
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateArrivalTime(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionBatchUpStockURL;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT, "批量修改零售二级现货到货时间");
        }
        /// <summary>
        /// 现货修改付款状态
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateReciptStatus(string param)
        {
            //前台传值统一参数名 免得混乱，新增与修改
            param = param.Replace("SourceDiscountReturn", "OriginDiscountReturn").Replace("SourceDolarPerGrain", "OriginUSDPerGrain").Replace("SourceDolarPerCarat", "OriginUSDPerCarat");
            logParam = param;
            HashParam hsParam = Json.Deserialize<HashParam>(param);
            string tttagKey = CommonUrl.getURL(hsParam, param, "零售一级现货修改付款状态");
            return CRetails.UpdateReciptStatus(hsParam, tttagKey);
        }

        /// <summary>
        /// 获取采购名称
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string GetPurchaseAgents(string param)
        {
            return CWholesalers.GetPurchaseAgents(param);
        }
        #endregion
        #region 现货修改买价 汇率
        /// <summary>
        /// 现货修改买价
        /// </summary>
        /// <param name="param">"filter":{"ID":["111","222"]},"factor":"1.1","field":"PurchaseUSDPerGrain"</param>
        /// <returns></returns>
        public string UpdateStockingPrice(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionUpBatchUrl;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT, "批量修改零售二级现货到货买价");
        }
        /// <summary>
        /// 现货修改汇率
        /// </summary>
        /// <param name="param">"filter":{"ID":["111","222"]},"value":"7","field":"PurchaseExchange"</param>
        /// <returns></returns>
        public string UpdatesStockingPurchaseExchange(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionUpBatchUrl;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT, "批量修改零售二级现货汇率");
        }
        public string OnStocksBatch(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionBatchUpStockURL;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT, "批量修改零售二级现货上架");
        }
        public string OffStocksBatch(string strParam)
        {
            string requestURL = GlobalConfig.TransmissionBatchUpStockURL;
            return CRetails.BatchUpdataDia(strParam, requestURL, MyHttpRequest.RequestLib.PUT, "批量修改零售二级现货下架");
        }
        /// <summary>
        /// 已知退点反推卖价
        /// </summary>
        /// <param name="IsFancy">是否彩钻1</param>
        /// <param name="ReturnPoint">退点</param>
        /// <param name="Rapnet"></param>
        /// <param name="Weight">重量</param>
        /// <param name="Discounts">客户的优惠</param>
        /// <param name="SourceDolarPerGrain">彩钻的原单粒价</param>
        /// <returns></returns>
        public decimal? CalcPriceUSD(int IsFancy, decimal? ReturnPoint, decimal? Rapnet, decimal? Weight, decimal? Discounts, decimal? SourceDolarPerGrain)
        {
            decimal? price = 0;
            if (IsFancy != 1)
            {
                //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                price = Rapnet * (100 + ReturnPoint) / 100 * Weight / Discounts;
            }
            else
            {
                //美元单粒价 		= 原单粒价 * (100 + 退点) / 100   
                price = SourceDolarPerGrain * (100 + ReturnPoint) / 100 / Discounts;
            }
            return price;
        }
        #endregion
        #region 购物车
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string AddCart(string strParam)
        {
            logParam = strParam;
            Cart cartinfo = null;
            HashParam HsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(HsParam, strParam);

            if (string.IsNullOrEmpty(HsParam.GetString("GoodsTypeID")))
            {
                return CommonLog.MsgErrorInfo("请选择添加的商品");
            }

            int goodType = HsParam.GetInt("GoodsTypeID").Value;

            CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(HsParam.GetInt("CustomerID"));//CustomerID必传
            if (customer != null)
            {
                string[] InventoryIDs = { };
                if (HsParam.ContainsKey("IDs"))
                    InventoryIDs = HsParam.GetString("IDs").TrimEnd(',').Split(',');
                else if (HsParam.ContainsKey("InventoryIDs"))
                    InventoryIDs = HsParam.GetString("InventoryIDs").TrimEnd(',').Split(',');
                List<int> failCount = new List<int>();
                List<int> succCount = new List<int>();
                List<Cart> cartList = new List<Cart>();
                for (int i = 0; i < InventoryIDs.Length; i++)
                {
                    Hashtable hash = new Hashtable();
                    hash.Add("CustomerID", customer.CustomerID);
                    hash.Add("GoodsTypeID", goodType);
                    hash.Add("GoodsID", InventoryIDs[i]);
                    cartinfo = YZ.GetDatabase(tttagKey).QueryForObject<Cart>("Cart.GetCart", hash);
                    if (cartinfo == null)
                    {
                        cartinfo = new Cart();
                        cartinfo.CustomerID = customer.CustomerID;//客户ID
                        //cartinfos.UserID = customer.SalesUserID; //业务ID
                        cartinfo.GoodsID = Convert.ToInt32(InventoryIDs[i]);
                        cartinfo.GoodsTypeID = goodType;
                        cartinfo.CartType = HsParam.GetInt("CartType").Value;
                        cartinfo.CreateTime = DateTime.Now;//加入购物车时间
                        cartList.Add(cartinfo); //用于sql加入购物车
                        succCount.Add(Convert.ToInt32(InventoryIDs[i])); //记录成功id

                    }
                    else
                    {
                        failCount.Add(Convert.ToInt32(InventoryIDs[i])); //记录失败id
                    }
                }
                using (ITransaction tran_addRingCart = YZ.GetTransaction(tttagKey))

                {
                    try
                    {
                        string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"succ\":#succ,\"fail\":#fail}"; //templateJSON
                        if (succCount.Count == 0)
                        {
                            return _msgInfo.Replace("#code", "true").Replace("#msg", "重复添加商品").Replace("#succ", JsonConvert.SerializeObject(succCount)).Replace("#fail", JsonConvert.SerializeObject(failCount));//.TrimEnd(',')为数组 Substring为字符串 Failed.Substring(0, Failed.Length - 1)
                        }
                        else
                        {
                            tran_addRingCart.Insert("Cart.AddCartInfoList", cartList);
                            tran_addRingCart.CommitTransaction(); //提交  
                            return _msgInfo.Replace("#code", "true").Replace("#msg", "加入购物车成功").Replace("#succ", JsonConvert.SerializeObject(succCount)).Replace("#fail", JsonConvert.SerializeObject(failCount));//.TrimEnd(',')为数组 Substring为字符串 Failed.Substring(0, Failed.Length - 1)

                        }
                    }
                    catch (Exception ex)
                    {
                        tran_addRingCart.RollBackTransaction();
                        return CommonLog.MsgErrorInfo("加入购物车失败");
                    }
                }

            }
            else
            {
                return CommonLog.MsgErrorInfo("客户信息未找到");
            }
        }

        /// <summary>
        ///  删除购物车
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string DeleteCart(string strParam)
        {
            return AllPublic.DeleteCart(strParam);
        }

        /// <summary>
        /// 提交订单成功后删除购物车
        /// </summary>
        /// <param name="goodType">商品类型</param>
        /// <param name="CustomerID">用户ID</param>
        /// <param name="Ids">商品ID</param>
        /// <returns></returns>
        public string DelCartInfo(int goodType, int CustomerID, int[] Ids, string tttageKey)
        {
            try
            {
                Hashtable hash = new Hashtable();
                hash.Add("CustomerID", CustomerID);
                hash.Add("GoodsTypeID", goodType);
                hash.Add("GoodsIDs", Ids);
                bool b = YZ.GetDatabase(tttageKey).Delete("Cart.DelCartInfoByIds", hash) > 0;
                if (b)
                {
                    return CommonLog.MsgSuccessInfo("移除成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("移除失败"); 
                }
            }
            catch (Exception ex)
            {
                return CommonLog.MsgErrorInfo("程序错误,"+ex.Message);
            }
        }

        /// <summary>
        /// 查询购物车
        /// </summary>
        /// <param name="selectParam"></param>
        /// <returns></returns>
        public string GetAllCartsList(string strParam)
        {
            logParam = strParam;
            string tttagKey = CommonUrl.getURL(null, strParam);
            Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(strParam));
            try
            {
                if (!(param.ContainsKey("CustomerID") || param.ContainsKey("openId")))
                {
                    return CommonLog.MsgErrorInfo("参数不正确");
                }
                int customerId = 0;
                if (param.ContainsKey("CustomerID"))
                {
                    int.TryParse(param["CustomerID"].ToString(), out customerId);
                }
                else if (param.ContainsKey("openId"))
                {
                    customerId = GetCustomerIdByOpenid(param["openId"].ToString(), tttagKey);
                }

                CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(customerId);//CustomerID必传
                IList<Cart> cartList = YZ.GetDatabase(tttagKey).QueryForList<Cart>("Cart.GetCart", param);
                Dictionary<string, object> dic2 = new Dictionary<string, object>();
                string token = string.Empty;
                if (param.ContainsKey("ParentKey"))
                {
                    token = param["ParentKey"].ToString();
                }
                foreach (var item in cartList)
                {
                    ProductList<object> list = GetCartInfo(customer, tttagKey, item.InventoryIDArray, item.GoodsTypeID, param);
                    if(list.Rows.Count>0)
                        dic2.Add(GoodsType.GetGoodsName(item.GoodsTypeID), list);
                }

                if (dic2.Count > 0)
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(dic2));
                else
                    return CommonLog.MsgErrorInfo("未添加商品到购物车");
            }
            catch (Exception ex)
            {

            }
            return CommonLog.MsgErrorInfo("Error");
        }

        public ProductList<object> GetCartInfo(CustomerInfo customer, string tttagKey, int[] inventIDs, int systemType, Hashtable param)
        {
            int goodsType = 0;
            string filterUrl = GoodsType.GetGoodsFilters(systemType, ref goodsType);
            SysSettingInfo settingInfo = GetSystemSetting(systemType, goodsType, tttagKey);
            var productIdsStr = CRetails.GetIdsStrParamByIds(inventIDs); //加入 useDict：true等元素 
             
            string responseJson = string.Empty;
            if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")//Mark是子级特有的标记  
            { 
                param["useDict"]= true; 
                param["ID"]= inventIDs;
                param["GoodsType"] = goodsType; 

                if (param["ErJiMark"].ToString() == "2LSto1LS")//数据来源 2级零售版本，它的数据来源是一级零售
                {
                    param.Remove("CustomerID");
                }
                else if (param["ErJiMark"].ToString() == "2LSto1PF")
                {
                    param.Remove("CustomerID");
                    param["TagKey"] = tttagKey.Split(new string[] { "__" }, StringSplitOptions.None)[0]; //上一级需要加上一级自己的key  
                    if (!param.ContainsKey("SecondSN"))
                        param.Add("SecondSN", tttagKey);
                }
                productIdsStr = JsonConvert.SerializeObject(param);
                if (goodsType == GoodsType.Diamond)
                {
                    responseJson = GetInventoryInfos(productIdsStr).Replace("TotalCount", "records").Replace("Data", "rows");
                }
                else
                {
                    responseJson = GetProductData(productIdsStr,"").Replace("TotalCount", "records").Replace("Data", "rows");
                }
                HashParam paramResult = JsonConvert.DeserializeObject<HashParam>(responseJson);
                if (paramResult.GetBool("msgcode"))
                {
                    var data = paramResult.GetString("data");
                    if(string.IsNullOrEmpty(data))
                    {
                        //其他商品返回和裸钻不一样
                        data = paramResult.GetString("msginfo");
                    }
                    paramResult = JsonConvert.DeserializeObject<HashParam>(data);
                    if(!paramResult.ContainsKey("result"))
                        paramResult.Add("result", true);
                    responseJson = JsonConvert.SerializeObject(paramResult);
                }
            }
            else
            {
                //一级零售查货
                responseJson = CRetails.AllProduct(tttagKey, productIdsStr, filterUrl);
            }
            //其它产品 没有OriginUSDPerGrain 这些字段，所以不用区分
            responseJson = responseJson.Replace("OriginUSDPerGrain", "SourceDolarPerGrain").Replace("OriginDiscountReturn", "SourceDiscountReturn").Replace("OriginUSDPerCarat", "SourceDolarPerCarat");
            ProductList<object> productList = null;// JsonConvert.DeserializeObject<ProductList<object>>(responseJson);
            if (goodsType == GoodsType.Diamond)
            {
                RemoteProduct<InventoryInfoResult> responseDict = JsonConvert.DeserializeObject<RemoteProduct<InventoryInfoResult>>(responseJson);

                if (responseDict != null && responseDict.result)
                {
                    if (responseDict.rows.Count > 0)  //非上传的货，计算价格
                    {
                        //计算客户及用户看到的价格
                        SysSettingInfo setting = GetSystemSetting(GoodsType.Diamond, 1, tttagKey);
                        DiamondsPriceHandlers diamondspricehandlers = new DiamondsPriceHandlers();
                        foreach (var item in responseDict.rows)
                        {
                            if (param.ContainsKey("ErJiMark") && param["ErJiMark"].ToString() != "")//Mark是子级特有的标记 则把一级得到的customer信息设置为原始信息开始计算
                            {
                                item.SourceDiscountReturn = item.CustomerDiscountReturn; //白钻用
                                item.SourceDolarPerGrain = item.CustomerDolarPerGrain; //彩钻用
                                //item.SourceDolarPerCarat = item.CustomerDolarPerCarat;
                            }
                            DiamondsPriceHandler.ComputePrice(tttagKey, item, setting, customer);//计算价格
                        }
                        var str = JsonConvert.SerializeObject(responseDict).Replace("rows", "Rows");
                        productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                    }
                }
            }
            else
            {
                SysSettingInfo setting = GetSystemSetting(goodsType, goodsType, tttagKey);

                //全局商品的倍率
                decimal settingRate = 1;
                //客户的倍率
                decimal customerRate = 1;
                if (customer != null)
                {
                    switch (goodsType)
                    {
                        case GoodsType.Diamond:
                            customerRate = customer.Rebate ?? 1; break;
                        case GoodsType.Ring:
                            customerRate = customer.RingRebate ?? 1; break;
                        case GoodsType.Parcel:
                            customerRate = customer.ParcelRebate ?? 1; break;
                        case GoodsType.Gem:
                            customerRate = customer.GemRebate ?? 1; break;
                        case GoodsType.Emerald:
                            customerRate = customer.EmeraldRebate ?? 1; break;
                        case GoodsType.PrimeGolds:
                            customerRate = customer.PrimeGoldRebate ?? 1; break;
                            //case GoodsType.InlaySettings:
                            //    customerDisc = customerInfo.InlaySettingsRebate ?? 1; break;
                    }
                }
                if (goodsType == GoodsType.Parcel)
                {
                    FromRemoteProducts<Parcels> fromRemoteProducts = JsonConvert.DeserializeObject<FromRemoteProducts<Parcels>>(responseJson);
                    foreach (var item in fromRemoteProducts.msginfo.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString() == "")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts.msginfo).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
                else if (goodsType == GoodsType.Ring)
                {
                    RemoteProduct<Ring> fromRemoteProducts = JsonConvert.DeserializeObject<RemoteProduct<Ring>>(responseJson);
                    foreach (var item in fromRemoteProducts.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString()=="")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
                else if (goodsType == GoodsType.Emerald)
                {
                    RemoteProduct<Emerald> fromRemoteProducts = JsonConvert.DeserializeObject<RemoteProduct<Emerald>>(responseJson);
                    foreach (var item in fromRemoteProducts.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString() == "")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
                else if (goodsType == GoodsType.Gem)
                {
                    RemoteProduct<Gem> fromRemoteProducts = JsonConvert.DeserializeObject<RemoteProduct<Gem>>(responseJson);
                    foreach (var item in fromRemoteProducts.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString() == "")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
                else if (goodsType == GoodsType.PrimeGolds)
                {
                    RemoteProduct<PrimeGolds> fromRemoteProducts = JsonConvert.DeserializeObject<RemoteProduct<PrimeGolds>>(responseJson);
                    foreach (var item in fromRemoteProducts.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString() == "")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        item.Price = item.TotalWeight * (item.GoldPrice + item.LaborFee) * supplierRate * settingRate * customerRate;
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
                else if (goodsType == GoodsType.InlaySettings)
                {
                    RemoteProduct<InlaySettings> fromRemoteProducts = JsonConvert.DeserializeObject<RemoteProduct<InlaySettings>>(responseJson);
                    foreach (var item in fromRemoteProducts.rows)
                    {
                        //供应商的倍率
                        decimal supplierRate = 1;
                        if (!param.ContainsKey("ErJiMark") || param["ErJiMark"].ToString() == "")//Mark是子级特有的标记 二级查询的价格已经经过全局和供应商的倍率计算
                        {
                            supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);
                            settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, Convert.ToDecimal(item.Price), tttagKey);
                        }
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率
                        {
                            decimal GoldPrice = Convert.ToDecimal(item.GoldPrice);
                            decimal NetGoldWeight = Convert.ToDecimal(item.NetGoldWeight);
                            decimal Wastage = Convert.ToDecimal(item.Wastage);
                            decimal SideLaborFee = Convert.ToDecimal(item.SideLaborFee);
                            decimal SideNum = Convert.ToDecimal(item.SideNum);
                            decimal SidePrice = Convert.ToDecimal(item.SidePrice);
                            decimal LaborFee = Convert.ToDecimal(item.LaborFee);
                            decimal Insurance = Convert.ToDecimal(item.Insurance);
                            decimal CustomerRMB = (GoldPrice * NetGoldWeight * (1 + Wastage)) + SideLaborFee * SideNum + SidePrice + LaborFee + Insurance;
                            if (customer != null)
                            {
                                if (customer.IsSetInlaySettings == 0)
                                {
                                    customerRate = (customer.InlaySettingsRebate == "" ? 1 : Convert.ToDecimal(customer.InlaySettingsRebate));
                                    //客户的折扣 *全局商品的倍率 * 供应商的倍率 
                                    item.Price = CustomerRMB * (1 + (supplierRate - 1) + (settingRate - 1) + (customerRate - 1));
                                    //反推出最后的结果
                                    item.CustomerGoldPrice = Math.Round(GoldPrice * customerRate);//金价
                                    item.CustomerWastage = item.Wastage;//损耗
                                    item.CustomerSideLaborFee = Math.Round(SideLaborFee * customerRate);//副石工费
                                    item.CustomerLaborFee = Math.Round(LaborFee * customerRate);//工费
                                    item.CustomerSidePrice = Math.Round(SidePrice * customerRate);//副石总额
                                    item.CustomerInsurance = Math.Round(Insurance * customerRate); //保险费 
                                }
                                else if (customer.IsSetInlaySettings == 1)
                                {
                                    CustomerSetInlaySetttings setInlaySetttings = Json.Deserialize<CustomerSetInlaySetttings>(customer.InlaySettingsRebate);
                                    //在原价的基础上 对客户设置空托的加价系数 得到的结果
                                    decimal CustomerRMB1 = ((GoldPrice + setInlaySetttings.GoldPrice) * NetGoldWeight * (1 + Wastage + setInlaySetttings.Wastage / 100)) //金价*净金重*（1+损耗）
                                                        + (SideLaborFee + setInlaySetttings.SideLaborFee) * SideNum//   副石工费 * 副石粒数
                                                        + (LaborFee * setInlaySetttings.LaborFee) //工费
                                                        + (SidePrice * setInlaySetttings.SidePrice) //副石总额
                                                        + (Insurance * setInlaySetttings.Insurance);//保险费
                                                                                                    //CustomerRMB1 /原卖价 得到一个相应的倍率  
                                    decimal resultDisc = (1 + (supplierRate - 1) + (settingRate - 1) + ((CustomerRMB1 / CustomerRMB) - 1));
                                    if (resultDisc == CustomerRMB1 / CustomerRMB)
                                    {
                                        //这是客户购买空托的时候 金价 损耗  副石工费  工费  副石总额  保险费
                                        item.CustomerGoldPrice = GoldPrice + setInlaySetttings.GoldPrice;//金价
                                        item.CustomerWastage = Wastage + setInlaySetttings.Wastage / 100;//损耗
                                        item.CustomerSideLaborFee = SideLaborFee + setInlaySetttings.SideLaborFee;//副石工费
                                        item.CustomerLaborFee = LaborFee * setInlaySetttings.LaborFee;//工费
                                        item.CustomerSidePrice = SidePrice * setInlaySetttings.SidePrice;//副石总额
                                        item.CustomerInsurance = Insurance * setInlaySetttings.Insurance; //保险费
                                    }
                                    else
                                    {
                                        //反推出最后的结果
                                        item.CustomerGoldPrice = Math.Round(GoldPrice * resultDisc);//金价
                                        item.CustomerWastage = Wastage;//损耗
                                        item.CustomerSideLaborFee = Math.Round(SideLaborFee * resultDisc);//副石工费
                                        item.CustomerLaborFee = Math.Round(LaborFee * resultDisc);//工费
                                        item.CustomerSidePrice = Math.Round(SidePrice * resultDisc);//副石总额
                                        item.CustomerInsurance = Math.Round(Insurance * resultDisc); //保险费 
                                    }
                                    item.Price = CustomerRMB * resultDisc;
                                }
                            }
                            else
                            {
                                item.Price = CustomerRMB * supplierRate * settingRate;
                            }
                        }
                    }
                    var str = JsonConvert.SerializeObject(fromRemoteProducts).Replace("rows", "Rows");
                    productList = JsonConvert.DeserializeObject<ProductList<object>>(str);
                }
            }
            return productList;
        }
        /// <summary>
        /// toDecimal
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private decimal _D(double d)
        {
            return Convert.ToDecimal(d);
        }
        /// <summary>
        /// toFloat
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private float _F(decimal d)
        {
            return float.Parse(d.ToString());
        }
        private static string GetGemIdsParamByCartInfoList(IList<CartResult> cartInfoList)
        {
            StringBuilder sbIds = new StringBuilder();
            foreach (var item in cartInfoList)
            {
                sbIds.Append("\"" + item.GoodsID + "\",");
            }
            return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
        }
        /// <summary>
        /// 查看购物车中的商品
        /// </summary>
        /// <param name="goodType">商品类别ID</param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string SearchCartInfo(int goodType, string param, string tttagKey)
        {
            try
            {
                logParam = param;
                //本地购物车id
                HashParam hash = JsonConvert.DeserializeObject<HashParam>(param);


                IList<CartResult> cartInfoList = YZ.GetDatabase(tttagKey).QueryForList<CartResult>("Cart.SearchCartInfoList", hash);//本地购物车是否存在加入
                if (cartInfoList != null && cartInfoList.Count > 0)
                {
                    string filterUrl = GoodsType.GetGoodsFilters(goodType, ref goodType);
                    var productIdsStr = GetGemIdsParamByCartInfoList(cartInfoList);

                     
                    string responseJson = string.Empty;
                    if (tttagKey.Contains("__")) //有二级key，则把一级得到的customer信息设置为原始信息开始计算
                    {
                        HashParam _param = JsonConvert.DeserializeObject<HashParam>(productIdsStr);
                        _param.Remove("TagKey");
                        _param.Add("TagKey", tttagKey);

                        if (!_param.ContainsKey("ParentKey"))
                            _param.Add("ParentKey", hash.GetString("ParentKey"));
                        if (!_param.ContainsKey("ErJiMark"))
                            _param.Add("ErJiMark", hash.GetString("ErJiMark"));
                        productIdsStr = JsonConvert.SerializeObject(_param);
                        responseJson = GetInventoryInfos(productIdsStr).Replace("TotalCount", "records").Replace("Data", "rows");
                        _param = JsonConvert.DeserializeObject<HashParam>(responseJson);
                        if (_param.GetBool("msgcode"))
                        {
                            var data = _param.GetString("data");
                            _param = JsonConvert.DeserializeObject<HashParam>(data);
                            _param.Add("result", true);
                            responseJson = JsonConvert.SerializeObject(_param);
                        }
                    }
                    else
                    {
                        responseJson = CRetails.AllProduct(tttagKey, productIdsStr, tttagKey, filterUrl);//得到仓库的数据
                    }




                    #region 裸钻
                    if (1 == goodType)
                    {
                        string _msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"succ\":#succ,\"fail\":#fail,\"totalrmbct\":#rmbct,\"totalrmb\":#rmb,\"totalusdct\":#usdct,\"totalusd\":#usd}";
                        int Successful = 0;//在库
                        int Failed = 0;//被抢购 
                        decimal? TotalCustomerRMBPerCarat = 0;//总每卡人民币
                        decimal? TotalCustomerRMBPerGrain = 0;//总人民币
                        decimal? TotalCustomerUSDPerCarat = 0;//总每卡人民币
                        decimal? TotalCustomerUSDPerGrain = 0;//总人民币
                        if (string.IsNullOrEmpty(responseJson))
                            return CommonLog.MsgErrorInfo("购物车被抢购");
                        else
                            responseJson = MyHttpRequest.ConvertToInventoryFormat(responseJson);
                        PageList<InventoryInfoResult> _doubleSellInventoryInfos = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(responseJson);
                        if (_doubleSellInventoryInfos != null && _doubleSellInventoryInfos.Data.Count > 0)
                        {
                            CustomerInfo customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(int.Parse(hash["CustomerID"].ToString()));//customerInfo为null
                            if (customerInfo == null)
                            {
                                return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("客户标识不存在")).Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed)).Replace("#rmbct", JsonConvert.SerializeObject(0)).Replace("#rmb", JsonConvert.SerializeObject(0));
                            }
                            Successful = _doubleSellInventoryInfos.Data.Count;//在库条目
                            Failed = cartInfoList.Count - Successful;//被抢购条目
                            SysSettingInfo setting = GetSystemSetting(GoodsType.Diamond, goodType, tttagKey);
                            //SystemSetting.tttagKey = key;
                            //SystemSetting setting = new SystemSetting();
                            //计算价格
                            DiamondsPriceHandler diamondspricehandlers = new DiamondsPriceHandler();
                            //转成字典方便获取对应Id的原始创建时间
                            var cartInfoListDict = cartInfoList.ToDictionary(t => t.GoodsID, t => t.CreateTime);
                            foreach (var item in _doubleSellInventoryInfos.Data)
                            {
                                //item.SourceDiscountReturn=item.CustomerDiscountReturn
                                DiamondsPriceHandler.ComputePrice(tttagKey, item, setting, customerInfo);
                                //统计 总人民币每卡 总人民币
                                TotalCustomerRMBPerCarat += item.CustomerRMBPerCarat;
                                TotalCustomerRMBPerGrain += item.CustomerRMBPerGrain;
                                TotalCustomerUSDPerCarat += item.CustomerDolarPerCarat;
                                TotalCustomerUSDPerGrain += item.CustomerDolarPerGrain;
                                //item.CreateTime = cartInfoListDict[item.InventoryID.Value].Value;//Cart原始创建下单时间排序
                            }
                            //按原始创建下单时间排序
                            var data = (IList<InventoryInfoResult>)_doubleSellInventoryInfos.Data.OrderByDescending(d => d.CreateTime).ToList();
                            _doubleSellInventoryInfos.Data = data;
                        }
                        else
                        {
                            //全部被抢购
                            //一旦全被抢购，清空本地购物车 11-16
                            #region
                            //清空购物车
                            YZ.GetDatabase(tttagKey).Delete("Cart.DelCartInfoByIds", hash);
                            #endregion
                            return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("购物车被抢购一空")).Replace("#succ", JsonConvert.SerializeObject(0)).Replace("#fail", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#rmbct", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#rmb", JsonConvert.SerializeObject(0)).Replace("#usdct", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#usd", JsonConvert.SerializeObject(0));
                        }
                        return _msgInfo.Replace("#code", "true").Replace("#msg", JsonConvert.SerializeObject(_doubleSellInventoryInfos)).Replace("#succ", JsonConvert.SerializeObject(Successful)).Replace("#fail", JsonConvert.SerializeObject(Failed)).Replace("#rmbct", JsonConvert.SerializeObject(TotalCustomerRMBPerCarat)).Replace("#rmb", JsonConvert.SerializeObject(TotalCustomerRMBPerGrain)).Replace("#usdct", JsonConvert.SerializeObject(TotalCustomerUSDPerCarat)).Replace("#usd", JsonConvert.SerializeObject(TotalCustomerUSDPerGrain));

                    }
                    #endregion
                    else
                    {
                        // RingInfoResult  list=JsonConvert.DeserializeObject<RingInfoResult>(responseJson);
                        //responseJson = MyHttpRequest.ConvertToInventoryFormat(responseJson);
                        HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(responseJson);
                        if (hsParam.Count > 0)
                        {
                            string ss = hsParam["rows"].ToString();
                            List<Dictionary<object, object>> listStr = JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(ss);
                            for (int i = 0; i < listStr.Count; i++)
                            {
                                string supplierCode = listStr[i]["Supplier"].ToString();

                                decimal iscount = GetDiscount(goodType, int.Parse(hash["CustomerID"].ToString()), supplierCode, tttagKey);
                                if (goodType == GoodsType.InlaySettings || goodType == GoodsType.PrimeGolds)
                                {
                                    listStr[i]["GoldPrice"] = Convert.ToDecimal(listStr[i]["GoldPrice"].ToString()) * iscount;
                                }
                                else
                                {
                                    listStr[i]["Price"] = Convert.ToDecimal(listStr[i]["Price"].ToString()) * iscount;
                                }
                            }
                            hsParam["rows"] = listStr;
                            responseJson = JsonConvert.SerializeObject(hsParam);
                        }
                        //decimal iscount = CommonClass.GetDiscount(goodType, int.Parse(hash["CustomerID"].ToString()), "0");

                    }
                    return CommonLog.MsgSuccessObj(responseJson);
                }
                else
                {
                    return CommonLog.MsgErrorInfo("购物车为空");
                }
            }
            catch (Exception ex)
            {
                return CommonLog.MsgErrorInfo("程序错误"+ex.Message);
            }
        }
        /// <summary>
        /// 获取折扣/退点
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="CustomerID"></param>
        /// <param name="supplierCode"></param>
        /// <returns></returns>
        public decimal GetDiscount(int goodType, int CustomerID, string supplierCode, string tttagKey)
        {
            DiamondsPriceHandler diamondspricehandlers = new DiamondsPriceHandler();
            //客户折扣
            decimal customerDisc = 1;
            //供应商折扣
            decimal supplierDisc = 1;

            CustomerInfo customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(Convert.ToInt32(CustomerID));
            //客户优惠
            decimal disc = customerInfo.Discounts ?? 1;

            switch (goodType)
            {
                case 1:
                    customerDisc = customerInfo.Rebate ?? 1; break;
                case 2:
                    customerDisc = customerInfo.RingRebate ?? 1; break;
                case 3:
                    customerDisc = customerInfo.ParcelRebate ?? 1; break;
                case 4:
                    customerDisc = customerInfo.GemRebate ?? 1; break;
                case 5:
                    customerDisc = customerInfo.EmeraldRebate ?? 1; break;
                case 6:
                    customerDisc = customerInfo.PrimeGoldRebate ?? 1; break;
            }
            switch (goodType)
            {
                case 1:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).Rebate ?? 1; break;
                case 2:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).RingRebate ?? 1; break;
                case 3:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).ParcelRebate ?? 1; break;
                case 4:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).GemRebate ?? 1; break;
                case 5:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).EmeraldRebate ?? 1; break;
                case 6:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(tttagKey, supplierCode).PrimeGoldRebate ?? 1; break;
            }
            if (disc == 0) disc = 1;
            if (supplierDisc == 0) supplierDisc = 1;
            if (customerDisc == 0) customerDisc = 1;
            var result = disc * customerDisc * supplierDisc;
            return result;
        }

        /// <summary>
        /// 查询客户购物车中商品的数量
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string getCartNumByCustomerID(string strParam)
        {
            logParam = strParam;
            HashParam hash = JsonConvert.DeserializeObject<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hash, strParam);
            int num = YZ.GetDatabase(tttagKey).QueryForObject<int>("Cart.GetCartNumByCustomerId", hash);
            var msg = new
            {
                CartNum = num
            };
            return JsonConvert.SerializeObject(msg);
        }
        #endregion

        #region  客户手机注册
        /// <summary>
        //客户修改密码（公司客户）
        /// </summary>
        /// <param name="customerModifyPasswordParam"></param>
        /// <returns></returns>
        public string CustomerModifyPassword(string customerModifyPasswordParam)
        {

            logParam = customerModifyPasswordParam;

            //客户标识、老密码、新密码
            //templateJSON
            HashParam param = Json.Deserialize<HashParam>(customerModifyPasswordParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, customerModifyPasswordParam);
            try
            {
                int _customerID = Convert.ToInt32(param.GetInt("CustomerID"));//客户标识(强制转换)
                string _oldPassword = param.GetString("OldUserPassword");//老密码
                string _newPassword = param.GetString("NewUserPassword");//新密码
                CustomerInfo customer = new CustomerInfo();
                customer.CustomerID = _customerID;
                customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(customer);
                if (customer != null)
                {
                    //判断老密码是否输入正确
                    if (Yunzuan.Foundation.Safe.EncryptHelper.MD5(_oldPassword) != customer.UserPassword)
                    {
                        return CommonLog.MsgErrorInfo("旧密码错误");
                    }
                    else
                    {
                        //设置新密码
                        customer.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(_newPassword);
                        int customerModifyPwdResult = YZ.GetDatabase(tttagKey).Edit(customer);
                        if (customerModifyPwdResult > 0)
                        {
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("修改失败,请重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("客户不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        /// <summary>
        /// 客户手机注册
        /// </summary>
        /// <param name="regInfo"></param>
        /// <returns></returns>
        public string CustomerLoginAndRegister(string regInfo)
        {
            logParam = regInfo;
            var _regInfo = regInfo;
            regInfo = regInfo.Replace("Tel", "Mobile").Replace("Pwd", "UserPassword"); //先兼容wap或其它注册
            HashParam param = JsonConvert.DeserializeObject<HashParam>(regInfo);
            string tttagKey = CommonUrl.getURL(param, regInfo,"客户登陆");
            var result = string.Empty;
            //验证码与手机号一定要有 
            if (param.ContainsKey("smsCode") && param.ContainsKey("Mobile"))
            {
                param = JsonConvert.DeserializeObject<HashParam>(regInfo);
                var cacheKey = "Cache:smsCode" + param["Mobile"];
                //验证验证码是否正确
                if (HttpRuntime.Cache.Get(cacheKey) != null && HttpRuntime.Cache.Get(cacheKey).ToString().ToLower() == param["smsCode"].ToString().ToLower())
                {
                    //判断是否存在，
                    if (IsNoRegister(_regInfo).Contains("true"))
                    {
                        CustomerInfo customer = JsonConvert.DeserializeObject<CustomerInfo>(regInfo);
                        //customer.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(customer.UserPassword);
                        customer.UserName = customer.Mobile;
                        customer.CreateTime = DateTime.Now;
                        customer.SysStatus = 1;
                        UserInfo user = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getSalesUserID", "");  //默认管理员
                        if (user != null)
                        {
                            customer.SalesUserID = user.UserID;
                            customer.OpenId = ""; //需要一个默认值
                            param.Add("SalesName", user.UserName); 
                            int i = YZ.GetDatabase(tttagKey).Add(customer);
                            if (i > 0)
                            {
                                //继续登录
                                //result=
                                result = CustomerLoginByRegister(param, tttagKey); 
                            }
                            else
                            {
                                result = CommonLog.MsgErrorInfo("失败");
                            }
                        }
                        else
                        {
                            result = CommonLog.MsgErrorInfo("暂时不能注册，系统尚未设置业务员");
                        }



                    }//已注册，直接登录
                    else
                    {
                        string _name = param.GetString("Mobile");//帐号 
                        //登录参数非空判断
                        if (string.IsNullOrEmpty(_name))
                        {
                            result = CommonLog.MsgErrorInfo("客户登录失败:帐号或密码为空");
                        }
                        //客户表Customer

                        result = CustomerLoginByRegister(param, tttagKey);
                    }
                }
                else
                {
                    result = CommonLog.MsgErrorInfo("验证码不正确");
                }
            }
            else
            {
                result = CommonLog.MsgErrorInfo("参数不正确");
            }
            return result;
        }

        private string CustomerLoginByRegister(HashParam param, string tttagKey)
        {
            string result = string.Empty;
            CustomerInfo _customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.Login", param.GetString("Mobile"));//通过用户名UserName
            if (_customer != null)
            {
                //客户帐号状态SysStatus（-1 已删除 0 已禁用 2 审核中 1正常）

                try
                {
                    //更新客户的登录次数LoginCount 、上次活跃时间LastActiveTime 和 活跃IP
                    _customer.ActiveIP = param.GetString("ActiveIP");
                    int customerLoginResult = YZ.GetDatabase(tttagKey).Edit(_customer);
                    if (customerLoginResult > 0)
                    { 
                        result = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_customer));
                        UserLoginLog userloginlog = new UserLoginLog();
                        userloginlog.HttpURL = param.GetString("HttpUrl");
                        userloginlog.tttagKey = tttagKey;
                        userloginlog.UserType = "1";//团队1，客户2
                        userloginlog.LoginUserID = _customer.CustomerID.ToString();
                        userloginlog.UserName = _customer.UserName;
                        userloginlog.ActiveIP = param.GetString("ActiveIP");
                        userloginlog.OprationDesc = "客户短信验证登陆";
                        userloginlog.CreateDate = DateTime.Now;
                        string strP = JsonConvert.SerializeObject(userloginlog);
                        ConmonMQMsgClass.send("登陆" + strP);
                        //result = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_customer)); 
                        //麦金麦钻需要业务名，这里封装下
                        HashParam _param = JsonConvert.DeserializeObject<HashParam>(JsonConvert.SerializeObject(_customer));
                        if (param.ContainsKey("SalesName"))
                        {
                            _param.Add("SalesName", param.GetString("SalesName", ""));
                        }
                        else
                        {
                            HashParam p = new HashParam();
                            p.Add("UserID", _customer.SalesUserID);
                            IList<UserInfo> user = YZ.GetDatabase(tttagKey).QueryForList<UserInfo>("User.getSalesByUserID", p);  //默认管理员
                            if (user == null || user.Count == 0)
                            {
                                _param.Add("SalesName", "");
                            }
                            else
                                _param.Add("SalesName", user[0].UserName);
                        }
                        result = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_param));

                    }
                    else
                    {
                        result = CommonLog.MsgErrorInfo("客户登录失败:数据库更新操作错误，请重试");
                    }
                }
                catch (Exception ex)
                {
                    GetMethodInfoAndWriteLogs(ex);
                    result = CommonLog.MsgErrorInfo("客户登录失败，程序错误");
                }
            }
            else
            {
                result = CommonLog.MsgErrorInfo("客户登录失败，没有对应客户信息");
            }
            return result;
        }
        /// <summary>
        /// 客户手机注册   合并前注册
        /// </summary>
        /// <param name="regInfo"></param>
        /// <returns></returns>
        public string Register(string regInfo)
        {
            logParam = regInfo;
            var _regInfo = regInfo;
            HashParam param = JsonConvert.DeserializeObject<HashParam>(regInfo);
            string tttagKey = CommonUrl.getURL(param, regInfo);

            if (param.ContainsKey("smsCode") && param.ContainsKey("Tel") || param.ContainsKey("smsCode") && param.ContainsKey("Mobile"))
            {
                regInfo = regInfo.Replace("Tel", "Mobile").Replace("Pwd", "UserPassword"); //先兼容wap或其它注册
                param = JsonConvert.DeserializeObject<HashParam>(regInfo);
                var cacheKey = "Cache:smsCode" + param["Mobile"];
                if (HttpRuntime.Cache.Get(cacheKey) != null && HttpRuntime.Cache.Get(cacheKey).ToString().ToLower() == param["smsCode"].ToString().ToLower())
                {
                    //判断是否存在，
                    if (IsNoRegister(_regInfo).Contains("true"))
                    {
                        CustomerInfo customer = JsonConvert.DeserializeObject<CustomerInfo>(regInfo);
                        //customer.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(customer.UserPassword);
                        customer.UserName = customer.Mobile;
                        customer.CreateTime = DateTime.Now;
                        customer.SysStatus = 1;
                        UserInfo user = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getSalesUserID", "");
                        if (user != null)
                            customer.SalesUserID = user.UserID;
                        else
                            return CommonLog.MsgErrorInfo("暂时不能注册，系统尚未设置业务员");
                        customer.OpenId = ""; //需要一个默认值
                        YZ.GetDatabase(tttagKey).Add(customer);
                        return CommonLog.MsgSuccessInfo("注册成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("已被注册");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("验证码不正确");
                }
            }
            else
            {
                return CommonLog.MsgErrorInfo("参数不正确");
            }
        }
        /// <summary>
        /// 验证手机是否注册
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string IsNoRegister(string param)
        {
            logParam = param;
            param = param.Replace("Tel", "Mobile");
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(_param, param);
            if (_param.ContainsKey("Mobile"))
            {
                var tel = _param["Mobile"].ToString();
                CustomerInfo customer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerByTel", tel);
                if (customer != null)
                {
                    if(customer.SysStatus != 1)
                        return CommonLog.MsgErrorInfo("无法注册");
                    else
                        return CommonLog.MsgErrorInfo("已被注册");
                }
                else
                {
                    return CommonLog.MsgSuccessInfo("可以注册");
                }
            }
            else
            {
                return CommonLog.MsgErrorInfo("发送失败");
            }
        }
        #endregion

        #region 导出
        /// <summary>
        /// 导出所有订单（仅管理员）
        /// </summary>
        /// <param name="downloadAllOrderParam"></param>
        /// <returns></returns>
        public string ExportAllOrder(string exportAllParam)
        {
            logParam = exportAllParam;
            HashParam param = Json.Deserialize<HashParam>(exportAllParam);
            string tttagKey = CommonUrl.getURL(param, exportAllParam);
            string FileName = "全部订单 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder(); 
                if (param.ContainsKey("OrderIDs"))
                {
                    param["OrderIDs"] = (param["OrderIDs"] as JArray).Select(p => int.Parse(p.ToString())).ToArray();//JArray to int []
                }
                IList<OrderInfoResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderInfoResult>("Order.ExportAllOrder", param);//订单IList                   
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>货号</td>");
                OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                OutFileContent.Append("<td>尺寸</td>");
                OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>证书号</td>");
                OutFileContent.Append("<td>国际报价</td>");
                OutFileContent.Append("<td>销售汇率</td>");
                OutFileContent.Append("<td>采购汇率</td>");
                OutFileContent.Append("<td>卖出退点</td>");
                OutFileContent.Append("<td>卖出RMB</td>");
                OutFileContent.Append("<td>卖出USD</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>姓名</td>");
                OutFileContent.Append("<td>业务员</td>");
                OutFileContent.Append("<td>采购员</td>");
                OutFileContent.Append("<td>原退点</td>");
                OutFileContent.Append("<td>买美金</td>");
                OutFileContent.Append("<td>买人民币</td>");
                OutFileContent.Append("<td>原货号</td>");
                OutFileContent.Append("<td>下单日期</td>");
                OutFileContent.Append("<td>发货日期</td>");
                OutFileContent.Append("<td>到货日期</td>");
                OutFileContent.Append("<td>出货单号</td>");
                OutFileContent.Append("<td>出货日期</td>");
                OutFileContent.Append("<td>出货备注</td>");
                OutFileContent.Append("<td>订单状态</td>");
                OutFileContent.Append("<td>收款状态</td>");
                OutFileContent.Append("<td>付款状态</td>");
                OutFileContent.Append("<td>收款日期</td>");
                OutFileContent.Append("<td>付款日期</td>");
                OutFileContent.Append("<td>客户备注</td>");
                OutFileContent.Append("<td>业务备注</td>");
                OutFileContent.Append("<td>采购备注</td>");
                OutFileContent.Append("<td>物流备注</td>");
                OutFileContent.Append("<td>订单类型</td>");
                OutFileContent.Append("<td>运费$</td>");  //12-24
                OutFileContent.Append("<td>回款(天)</td>");
                OutFileContent.Append("<td>利润￥</td>");
                OutFileContent.Append("<td>实得￥</td>");
                OutFileContent.Append("<td>已扣￥</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(OrderList[i].InventoryAttribute);
                        //计算利润提成等-新 12-24
                        #region
                        foreach (var item in OrderList)
                        {
                            //计算回款天数
                            //当订单已支付，回款天数 = 支付日期 - 出货日期或到货日期  (固定) //当订单未支付，回款天数 = 当前日期 - 出货日期或到货日期  （灵活）
                            if (item.PaymentStatus == 1)
                            {
                                if (item.PaymentTime != null)
                                {
                                    //已出货
                                    if (item.ShipTime != null)
                                    {
                                        TimeSpan ts = Convert.ToDateTime(item.PaymentTime) - Convert.ToDateTime(item.ShipTime);   //DateTime.Now - item.ShipTime;//回款（天） = 当前日期 - 出货日期
                                        item.PaybackPeriods = ts.TotalDays; //TotalDays                            
                                    }
                                    else if (item.ArrivalTime != null)
                                    {
                                        //待出货
                                        TimeSpan ts = Convert.ToDateTime(item.PaymentTime) - Convert.ToDateTime(item.ArrivalTime); //DateTime.Now - item.ArrivalTime;//回款（天） = 当前日期 - 到货日期
                                        item.PaybackPeriods = ts.TotalDays; //TotalDays
                                    }
                                }
                            }
                            else
                            {
                                if (item.ShipTime != null)
                                {
                                    TimeSpan ts = DateTime.Now - Convert.ToDateTime(item.ShipTime);   //DateTime.Now - item.ShipTime;//回款（天） = 当前日期 - 出货日期
                                    item.PaybackPeriods = ts.TotalDays; //TotalDays                            
                                }
                                else
                                {
                                    TimeSpan ts = DateTime.Now - Convert.ToDateTime(item.ArrivalTime); //DateTime.Now - item.ArrivalTime;//回款（天） = 当前日期 - 到货日期
                                    item.PaybackPeriods = ts.TotalDays; //TotalDays
                                }
                            }
                            //计算运费 必须为decimal?否则无法判断==null
                            if (item.Freight == 0)
                            {
                                //动态计算
                                if (item.Supplier.ToLower() == tttagKey)  //GlobalConfig.SelfStock 现货供应商简称 11-26
                                {
                                    item.Freight = 0;  //现货运费为0
                                }
                                else
                                {
                                    item.Freight = Convert.ToDecimal(item.PurchaseUSD * Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["BaseFreight"])); //运费$ = 买入$ * 0.004 (12-3启用)
                                }
                            }
                            //if (item.PurchaseRMB == null)
                            //{
                            //    item.PurchaseRMB = Convert.ToDecimal((item.PriceUSD + item.Freight) * item.PurchaseExchangerate); //买入RMB = (买入美金 + 运费美金)* 采购汇率 （12-3启用）
                            //}
                            item.Profits = Convert.ToDecimal(item.ConfirmRMB - item.PurchaseRMB); //利润 = 卖￥ - 买 ￥ (12-3启用)
                                                                                                  //计算提成
                                                                                                  //已出货订单 利润 x 30% x (15 - 回款天数) 已定      5天为界限  从第6天起每天减少10%     //待出货订单 利润 x 30% x (15 - 回款天数) 已定
                            if (item.OrderStatus == 4 || item.OrderStatus == 3)
                            {
                                //如果有利润才有提成 11-11
                                if (item.Profits > 0)
                                {
                                    item.DesertRoyalties = item.Profits * Convert.ToDecimal(0.3);
                                    if (item.PaybackPeriods > 15)
                                    {
                                        item.Royalties = 0;//提成为0
                                    }
                                    else if (item.PaybackPeriods > 5)
                                    {
                                        item.Royalties = item.Profits * Convert.ToDecimal(0.3) * Convert.ToDecimal(((15 - item.PaybackPeriods) * 0.1));
                                    }
                                    else
                                    {
                                        item.Royalties = item.Profits * Convert.ToDecimal(0.3);
                                    }
                                }
                                else
                                {
                                    item.Royalties = 0;//无利润 提成为0
                                    item.DesertRoyalties = 0;
                                }
                            }
                        }
                        #endregion
                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + _inventory.SN + "</td>");
                        columnValue.Append("<td>" + ShapeFormat(_inventory.Shape) + "</td>");
                        columnValue.Append("<td>" + _inventory.Weight + "</td>");
                        columnValue.Append("<td>" + _inventory.Color + "</td>");
                        columnValue.Append("<td>" + _inventory.Clarity + "</td>");
                        columnValue.Append("<td>" + _inventory.Cut + "</td>");
                        columnValue.Append("<td>" + _inventory.Polish + "</td>");
                        columnValue.Append("<td>" + _inventory.Symmetry + "</td>");
                        columnValue.Append("<td>" + _inventory.Fluorescence + "</td>");
                        columnValue.Append("<td>" + _inventory.Measurement + "</td>");
                        columnValue.Append("<td>" + _inventory.CertType + "</td>");
                        columnValue.Append("<td>" + _inventory.CertNo + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmRMB + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmUSD + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerRealName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesUserName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseUserName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseUSD + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseRMB + "</td>");//PurchasedRMB PurchaseRMB
                        columnValue.Append("<td>" + _inventory.OriginSN + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].CreateTime) + "</td>");//09-19
                        columnValue.Append("<td>" + ConventTime(OrderList[i].ShipTime) + "</td>");//9-19
                        columnValue.Append("<td>" + OrderList[i].ArrivalTime + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ShipNo + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].ShipTime) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ShipRemarks + "</td>");
                        columnValue.Append("<td>" + OrderStatusFormat(OrderList[i].OrderStatus) + "</td>");
                        columnValue.Append("<td>" + PaymentStatusFormat(OrderList[i].PaymentStatus) + "</td>");
                        columnValue.Append("<td>" + ReceiptStatusFormat(OrderList[i].ReceiptStatus) + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].PaymentTime) + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].RecTime) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Remarks + "</td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("<td>" + OrderTypeFormat(OrderList[i].UserID) + "</td>");//订单类型
                        columnValue.Append("<td>" + OrderList[i].Freight + "</td>"); // 11-5
                        columnValue.Append("<td>" + OrderList[i].PaybackPeriods + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Profits + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Royalties + "</td>");//实得提成
                        columnValue.Append("<td>" + (OrderList[i].DesertRoyalties - OrderList[i].Royalties) + "</td>");//已扣提成
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + OrderList.Count+ "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                                                                                                                                                                                      //返回文件下载地址 http://localhost:3952/excel/2016-08-18 08-03-03.xls
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出订单失败:");
            }
        }

        /// <summary>
        /// 导出销售和采购订单（团队）
        /// </summary>
        /// <returns></returns>
        public string DownloadAllOrder(string downloadAllOrderParam)
        {
            logParam = downloadAllOrderParam;
            HashParam param = Json.Deserialize<HashParam>(downloadAllOrderParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, downloadAllOrderParam);
            string FileName = "销售和采购订单 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<OrderResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderResult>("Order.ExportOrder", param);//订单IList
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>货号</td>");
                OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                //OutFileContent.Append("<td>尺寸</td>");
                OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>证书号</td>");
                OutFileContent.Append("<td>国际报价</td>");
                OutFileContent.Append("<td>销售汇率</td>");
                OutFileContent.Append("<td>采购汇率</td>");
                OutFileContent.Append("<td>卖出退点</td>");
                OutFileContent.Append("<td>卖出RMB</td>");
                OutFileContent.Append("<td>卖出USD</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>姓名</td>");
                OutFileContent.Append("<td>业务员</td>");
                OutFileContent.Append("<td>采购员</td>");
                OutFileContent.Append("<td>供应商</td>");
                OutFileContent.Append("<td>原退点</td>");
                OutFileContent.Append("<td>买美金</td>");
                OutFileContent.Append("<td>买人民币</td>");
                OutFileContent.Append("<td>原货号</td>");
                OutFileContent.Append("<td>下单日期</td>");
                OutFileContent.Append("<td>发货日期</td>");
                OutFileContent.Append("<td>到货日期</td>");
                OutFileContent.Append("<td>订单状态</td>");
                OutFileContent.Append("<td>收款状态</td>");
                OutFileContent.Append("<td>付款状态</td>");
                OutFileContent.Append("<td>客户备注</td>");
                OutFileContent.Append("<td>业务备注</td>");
                OutFileContent.Append("<td>采购备注</td>");
                OutFileContent.Append("<td>物流备注</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(OrderList[i].InventoryAttribute);

                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + _inventory.SN + "</td>");
                        columnValue.Append("<td>" + ShapeFormat(_inventory.Shape) + "</td>");
                        columnValue.Append("<td>" + _inventory.Weight + "</td>");
                        columnValue.Append("<td>" + _inventory.Color + "</td>");
                        columnValue.Append("<td>" + _inventory.Clarity + "</td>");
                        columnValue.Append("<td>" + _inventory.Cut + "</td>");
                        columnValue.Append("<td>" + _inventory.Polish + "</td>");
                        columnValue.Append("<td>" + _inventory.Symmetry + "</td>");
                        columnValue.Append("<td>" + _inventory.Fluorescence + "</td>");
                        columnValue.Append("<td>" + _inventory.CertType + "</td>");
                        columnValue.Append("<td>" + _inventory.CertNo + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmRMB + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmUSD + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerRealName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesUserName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseUserName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Supplier + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseUSD + "</td>");
                        columnValue.Append("<td>" + OrderList[i].PurchaseRMB + "</td>");
                        columnValue.Append("<td>" + _inventory.OriginSN + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].CreateTime) + "</td>");//09-19
                        columnValue.Append("<td>" + ConventTime(OrderList[i].ShipTime) + "</td>");//9-19
                        columnValue.Append("<td>" + OrderList[i].ArrivalTime + "</td>");
                        columnValue.Append("<td>" + OrderStatusFormat(OrderList[i].OrderStatus) + "</td>");
                        columnValue.Append("<td>" + PaymentStatusFormat(OrderList[i].PaymentStatus) + "</td>");
                        columnValue.Append("<td>" + ReceiptStatusFormat(OrderList[i].ReceiptStatus) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Remarks + "</td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("<td></td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + OrderList.Count+ "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    //返回文件下载地址 http://localhost:3952/excel/2016-08-18 08-03-03.xls
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出订单失败:");
            }
        }

        /// <summary>
        /// 导出 今日取货单 （仅管理员和物流）
        /// </summary>
        /// <param name="exportDeliveryOrderParam"></param>
        /// <returns></returns>
        public string DeliveryOrders(string deliveryOrdersParam)
        {
            logParam = deliveryOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(deliveryOrdersParam);
            string tttagKey = CommonUrl.getURL(param, deliveryOrdersParam);
            string FileName = "今日取货单 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<OrderResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderResult>("Order.DeliveryOrders", param);//生成 9-28
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>编号</td>");
                OutFileContent.Append("<td>供应商</td>");
                OutFileContent.Append("<td>原货号</td>");
                OutFileContent.Append("<td>证书号</td>");
                //OutFileContent.Append("<td>货号</td>");
                //OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                //OutFileContent.Append("<td>尺寸</td>");
                //OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>国际报价</td>");
                //OutFileContent.Append("<td>销售汇率</td>");
                //OutFileContent.Append("<td>采购汇率</td>");
                //OutFileContent.Append("<td>卖出退点</td>");
                //OutFileContent.Append("<td>卖出RMB</td>");
                //OutFileContent.Append("<td>昵称</td>");
                //OutFileContent.Append("<td>姓名</td>");
                //OutFileContent.Append("<td>业务员</td>");
                OutFileContent.Append("<td>原退点</td>");
                OutFileContent.Append("<td>原美金</td>");
                OutFileContent.Append("<td>下单日期</td>");
                OutFileContent.Append("<td>发货日期</td>");
                OutFileContent.Append("<td>取货地址</td>");
                OutFileContent.Append("<td>货品描述</td>");
                OutFileContent.Append("<td>采购员</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>退还</td>");
                OutFileContent.Append("<td>业务采购备注</td>");
                //OutFileContent.Append("<td>到货日期</td>");
                //OutFileContent.Append("<td>订单状态</td>");
                //OutFileContent.Append("<td>支付状态</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(OrderList[i].InventoryAttribute);

                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Supplier + "</td>");
                        columnValue.Append("<td>" + _inventory.OriginSN + "</td>");
                        columnValue.Append("<td>" + _inventory.CertNo + "</td>");
                        columnValue.Append("<td>" + _inventory.Weight + "</td>");
                        columnValue.Append("<td>" + _inventory.Color + "</td>");
                        columnValue.Append("<td>" + _inventory.Clarity + "</td>");
                        columnValue.Append("<td>" + _inventory.Cut + "</td>");
                        columnValue.Append("<td>" + _inventory.Polish + "</td>");
                        columnValue.Append("<td>" + _inventory.Symmetry + "</td>");
                        columnValue.Append("<td>" + _inventory.Fluorescence + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmUSD + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].CreateTime) + "</td>");
                        columnValue.Append("<td>" + ConventTime(OrderList[i].ShipTime) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].DeliveryAddress + "</td>");
                        columnValue.Append("<td>" + _inventory.Milky + " " + _inventory.Hue + "</td>");//货品奶咖 9-14
                        columnValue.Append("<td>" + OrderList[i].PurchaseUserName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");//客户昵称 9-14
                        columnValue.Append("<td>" + "" + "</td>");//退 9-14
                        columnValue.Append("<td>" + OrderList[i].Remarks + "</td>");//取货备注（业务备注+采购备注） 9-14 
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计 
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    //返回文件下载地址 http://localhost:3952/excel/2016-08-18 08-03-03.xls
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在，今日无取货单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出取货单失败:");
            }
        }
        /// <summary>
        /// 导出销售订单（团队）
        /// </summary>
        /// <param name="downloadOrderParam"></param>
        /// <returns></returns>
        public string DownloadOrder(string downloadOrderParam)
        {
            logParam = downloadOrderParam;
            HashParam param = Json.Deserialize<HashParam>(downloadOrderParam); //解析客户端（pc ios android）传过来的Json (将Json格式为HashParam)  （Deserialize 反序列化）
            string tttagKey = CommonUrl.getURL(param, downloadOrderParam);
            string FileName = "销售订单 " + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + ".xls";//文件名 2016-08-18 03-28-20.xls
            StreamWriter sw;
            string FileUrl = HttpContext.Current.Server.MapPath("/excel/") + FileName;//文件存放的目录
            //如果文件不存在则创建该文件
            if (!File.Exists(FileUrl))
            {
                FileInfo file = new FileInfo(FileUrl);
                FileStream fs = file.Create();//创建文件
                fs.Close();
            }
            sw = new StreamWriter(FileUrl, false, Encoding.GetEncoding(-0));
            try
            {
                var isAdmin = true;
                if (param.GetString("SalesUserID") != "" && param.GetInt("SalesUserID") > 0) //判断是否是销售,不为销售即管理员，采购目前没有导出功能
                {
                    isAdmin = false;
                }
                StringBuilder Titlebuilder = new StringBuilder();
                StringBuilder OutFileContent = new StringBuilder();
                StringBuilder columnValue = new StringBuilder();
                IList<OrderResult> OrderList = YZ.GetDatabase(tttagKey).QueryForList<OrderResult>("Order.ExportOrder", param);//订单IList
                Titlebuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=gb2312' http-equiv='Content-Type' /></head><body>");
                Titlebuilder.Append("<table style='border-collapse:collapse;font-size:12px; text-align:center; border:1px solid #d1d7e5'>");//border='1px' bordercolor='#000000' cellspacing='0px' style='border-collapse:collapse;font-size:12px; text-align:center'
                OutFileContent.Append("<tr style='height:35px;text-align:center;border:1px solid #d1d7e5'>");
                OutFileContent.Append("<td>序号</td>");
                OutFileContent.Append("<td>货号</td>");
                OutFileContent.Append("<td>形状</td>");
                OutFileContent.Append("<td>重量</td>");
                OutFileContent.Append("<td>颜色</td>");
                OutFileContent.Append("<td>净度</td>");
                OutFileContent.Append("<td>切工</td>");
                OutFileContent.Append("<td>抛光</td>");
                OutFileContent.Append("<td>对称</td>");
                OutFileContent.Append("<td>荧光</td>");
                OutFileContent.Append("<td>证书</td>");
                OutFileContent.Append("<td>证书号</td>");
                OutFileContent.Append("<td>国际报价</td>");
                OutFileContent.Append("<td>销售汇率</td>");
                OutFileContent.Append("<td>卖出退点</td>");
                OutFileContent.Append("<td>卖出RMB</td>");
                OutFileContent.Append("<td>卖出USD</td>");
                OutFileContent.Append("<td>昵称</td>");
                OutFileContent.Append("<td>姓名</td>");
                OutFileContent.Append("<td>下单日期</td>");
                OutFileContent.Append("<td>订单状态</td>");
                OutFileContent.Append("<td>支付状态</td>");
                OutFileContent.Append("<td>客户备注</td>");
                OutFileContent.Append("</tr>");
                //Titlebuilder.Append("<tr><td colspan='30'><b>导出全部订单</b></td></tr>");
                sw.WriteLine(Titlebuilder);
                sw.WriteLine(OutFileContent);//写入标题行
                if (OrderList != null && OrderList.Count > 0)
                {
                    for (int i = 0; i < OrderList.Count; i++)
                    {
                        Inventory _inventory = JsonConvert.DeserializeObject<Inventory>(OrderList[i].InventoryAttribute);

                        columnValue.Clear();
                        columnValue.Append("<tr style='height:25px;text-align:center;border:1px solid #d1d7e5'>");//行开始
                        columnValue.Append("<td>" + (i + 1) + "</td>");
                        columnValue.Append("<td>" + _inventory.SN + "</td>");
                        columnValue.Append("<td>" + ShapeFormat(_inventory.Shape) + "</td>");
                        columnValue.Append("<td>" + _inventory.Weight + "</td>");
                        columnValue.Append("<td>" + _inventory.Color + "</td>");
                        columnValue.Append("<td>" + _inventory.Clarity + "</td>");
                        columnValue.Append("<td>" + _inventory.Cut + "</td>");
                        columnValue.Append("<td>" + _inventory.Polish + "</td>");
                        columnValue.Append("<td>" + _inventory.Symmetry + "</td>");
                        columnValue.Append("<td>" + _inventory.Fluorescence + "</td>");
                        columnValue.Append("<td>" + _inventory.CertType + "</td>");
                        columnValue.Append("<td>" + _inventory.CertNo + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Rapnet + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesExchangerate + "</td>");
                        columnValue.Append("<td>" + OrderList[i].SalesReturn + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmRMB + "</td>");
                        columnValue.Append("<td>" + OrderList[i].ConfirmUSD + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerNickName + "</td>");
                        columnValue.Append("<td>" + OrderList[i].CustomerRealName + "</td>");
                        columnValue.Append("<td>" + Convert.ToDateTime(OrderList[i].CreateTime).ToString("yyyy-MM-dd").Replace("0001-01-01", "-") + "</td>");//09-19
                        columnValue.Append("<td>" + OrderStatusFormat(OrderList[i].OrderStatus) + "</td>");
                        columnValue.Append("<td>" + PaymentStatusFormat(OrderList[i].PaymentStatus) + "</td>");
                        columnValue.Append("<td>" + OrderList[i].Remarks + "</td>");
                        columnValue.Append("</tr>");//行结束
                        sw.WriteLine(columnValue);
                    }
                    OutFileContent.Clear();
                    #region 统计
                    //OutFileContent.Append("<tr>");
                    //OutFileContent.Append("<td>" + OrderList.Count+ "</td><td></td></tr>");
                    #endregion
                    OutFileContent.Append("</table></body></html>");
                    sw.WriteLine(OutFileContent);
                    sw.Close();
                    return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    //返回文件下载地址 http://localhost:3952/excel/2016-08-18 08-03-03.xls
                }
                else
                {
                    return CommonLog.MsgErrorInfo("文件不存在,没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("导出订单失败:");
            }
        }
        public string ConventTime(DateTime? times)
        {
            return (times != null ? Convert.ToDateTime(times).ToString("yyyy-MM-dd").Replace("0001-01-01", "-") : "");
        }
        #endregion

        #region  微信登录相关
        /// <summary>
        /// 添加微信登录的用户信息
        /// </summary>
        /// <param name="param"></param>
        /// <param name="type">微信用户类型，默认公众号用户</param>
        /// <returns></returns>
        public bool AddWXCustomer(string tttagKey, string param, int type = 0)
        {
            bool isAdd = false;
            try
            {
                logParam = param;

                // param="{\"subscribe\":1,\"openid\":\"oCfARuNyrq7lNQfX0GsRo6PJJn78\",\"nickname\":\"何平子\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"深圳\",\"province\":\"广东\",\"country\":\"中国\",\"headimgurl\":\"http:\/\/thirdwx.qlogo.cn\/mmopen\/EDViaeugsgfOz5l5ibrSzAso4pNQZSNlNicTPkSpALJd7ibuborJFh12ic5PJNaftiam7yMKGywICV3cnXmlOvE48ia31Bic9w2vjjkV\/132\",\"subscribe_time\":1519986576,\"remark\":\"\",\"groupid\":0,\"tagid_list\":[]}";
                //GetMethodInfoAndWriteLogs(null, param);
                //yz_wechat_common 表
                WechatXcxInfo wechatInfo = JsonConvert.DeserializeObject<WechatXcxInfo>(param);
                wechatInfo.user_type = type;
                Logger.Error(this.GetType(), "--------------" + JsonConvert.SerializeObject(wechatInfo));
                var dbCustomer = YZ.GetDatabase(tttagKey).QueryForObject<CustomerInfo>("Customer.GetCustomerByOpenid", wechatInfo.openid);
                if (dbCustomer == null)
                {
                    Logger.Error(this.GetType(), "-------1111-------");
                    //没有就添加
                    // 添加 yz_wechat_common 表
                    WechatXcxInfo wechat = YZ.GetDatabase(tttagKey).QueryForObject<WechatXcxInfo>("WxInfo.GetUserByOpenid", wechatInfo.openid);
                    if (wechat != null)
                        isAdd = true;
                    else
                        isAdd = YZ.GetDatabase(tttagKey).Add(wechatInfo) > 0;
                    Logger.Error(this.GetType(), "-------222-------" + (isAdd ? "111" : "222"));
                    if (isAdd)
                    {
                        UserInfo user = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getSalesUserID", "");  //默认管理员
                        if (user != null)
                        {
                            CustomerInfo _customer = new CustomerInfo();
                            _customer.UserName = wechatInfo.openid;
                            _customer.UserPassword = Yunzuan.Foundation.Safe.EncryptHelper.MD5(wechatInfo.openid);
                            _customer.NickName = wechatInfo.nickname;
                            _customer.OpenId = wechatInfo.openid;
                            _customer.Sex = (short)wechatInfo.sex;
                            _customer.SysStatus = 1;
                            _customer.UpdateTime = DateTime.Now;
                            _customer.SalesUserID = user.UserID;
                            Logger.Error(this.GetType(), "-------准备添加-------" + JsonConvert.SerializeObject(wechatInfo));
                            isAdd = YZ.GetDatabase(tttagKey).Add(_customer) > 0;
                            Logger.Error(this.GetType(), "-------返回结果-------" + (isAdd ? "333" : "444"));
                            if (!isAdd)
                            {
                                GetMethodInfoAndWriteLogs(null, string.Format("微信表写入成功:{0},但是新增用户表失败:{1}", JsonConvert.SerializeObject(wechatInfo), JsonConvert.SerializeObject(_customer)));
                            }
                        }
                        else
                        {
                            GetMethodInfoAndWriteLogs(null, string.Format("微信表写入成功:{0}，暂时不能注册，系统尚未设置业务员", JsonConvert.SerializeObject(wechatInfo)));
                            isAdd = false;
                        }
                    }
                    else
                    {
                        Logger.Error(this.GetType(), "-------微信表写入失败-------" + JsonConvert.SerializeObject(wechatInfo));
                        GetMethodInfoAndWriteLogs(null, string.Format("微信表写入失败:{0}", JsonConvert.SerializeObject(wechatInfo)));
                        isAdd = false;
                    }
                }
                else
                {
                    //有直接返回
                    isAdd = true;
                }
            }
            catch (Exception ex)
            {

                Logger.Error(this.GetType(), string.Format("-AddWXCustomer param:{0}, 错误信息：{1}", param, ex.Message));
                GetMethodInfoAndWriteLogs(ex);
            }
            return isAdd;

        }

        #endregion

        #region 此处存放首页特定栏目相关的函数

        const string edit = "edit";
        const string add = "add";
        const string del = "del";
        const string stringStr = "string";
        const string intStr = "int";
        //本店产品
        public string GetProducts(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            return GetListFunc<Index_Product>("IndexProduct.GetProducts", null, tttagKey);
        }
     

        public string EditProduct(string param)
        {
            return OperateFunc<Index_Product>(param,edit);
        }


        //品牌介绍
        public string GetBrand(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            Index_Brand brand = YZ.GetDatabase(tttagKey).Get<Index_Brand>(1);
            return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(brand));
        }
        public string EditBrand(string param)
        {
            return OperateFunc<Index_Brand>(param,edit);
        }
        //预约进店
        public string GetAppointment(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            return GetListFunc<Index_Appointment>("IndexAppointment.GetAppointments", null, tttagKey);
        }


        //新闻，  //帮助中心support center

        public string GetArticles(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            return GetListFunc<Index_Articles>("IndexArticles.GetArticles", param, tttagKey);
        }


        public string EditArticles(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles>(param,edit); 
        }
        public string DelArticles(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles>(param, del);
        }
        public string AddArticles(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param, "ArticlesTypeID");
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles>(param, add);
        }
        public string GetArticlesFlag(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            return GetListFunc<Index_Articles_Flag>("IndexArticlesFlag.GetArticlesFlag", param, tttagKey);
        }
        

        public string EditArticlesFlag(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles_Flag>(param, edit);
        }
        public string DelArticlesFlag(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles_Flag>(param, del);
        }
        public string AddArticlesFlag(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail,param, "ArticlesTypeName", stringStr);
            if (isFail)
                return resultMsg;
            return OperateFunc<Index_Articles_Flag>(param, add);
        }
        /// <summary>
        /// 执行函数前的验证,主要用来检查id，类型id等,如需其它多个参数请自行拓展
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private static string ExeMethodCheckParam(out bool isFail, string param,string typeId= "ID",string typeStr=intStr)
        {
            isFail = false;
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(param);
            string resultMsg = string.Empty;
            if (typeStr == stringStr || typeStr == intStr)
            {
                if (typeStr == stringStr)
                {
                    typeId = _param.GetString(typeId, "0");
                }
                else
                {
                    typeId = _param.GetInt(typeId, 0).ToString();
                }
                if (typeId == "0")
                {
                    isFail = true;
                    resultMsg = CommonLog.MsgErrorInfo("失败,参数缺少" + typeId);
                }
            }
            else
            {
                isFail = true;
                resultMsg = CommonLog.MsgErrorInfo("失败,参数类型不支持,"+typeStr);
            }
            
            return resultMsg;
        }


        //预约进店录入
        public string AddAppointment(string param)
        {
            return OperateFunc<Index_Appointment>(param,add);
        }
      


        //通用操作函数
        private static string OperateFunc<T>(string param, string operateTag) where T : BaseEntity
        {
            string msgInfo =string.Empty;
            try
            {
                string tttagKey = CommonUrl.getURL(null, param);
                var obj = JsonConvert.DeserializeObject<T>(param);
                int count = 0;
                switch (operateTag)
                {
                    case "add":
                        msgInfo = "添加";
                        count = YZ.GetDatabase(tttagKey).Add(obj);
                        break;
                    case "edit":
                        msgInfo = "更新";
                        count=YZ.GetDatabase(tttagKey).Edit(obj);
                        break;
                    case "del":
                        msgInfo = "删除";
                        count = YZ.GetDatabase(tttagKey).Delete(obj);
                        break; 
                }
                if (count > 0)
                {
                    return CommonLog.MsgSuccessInfo(msgInfo + "成功");
                }
                else
                    return CommonLog.MsgErrorInfo( msgInfo + "失败");
            }
            catch (Exception ee)
            {
                return CommonLog.MsgErrorInfo(msgInfo + "失败,原因：" + ee.Message);
            }

        }
         
        //通用查询列表函数
        private static string GetListFunc<T>(string sql, string param, string tttagKey) where T : BaseEntity
        {
            try
            {
                HashParam _param = new HashParam();
                if (param != null)
                    _param = JsonConvert.DeserializeObject<HashParam>(param);
                else
                    _param = null;
                var lists = YZ.GetDatabase(tttagKey).QueryForList<T>(sql, _param);
                if (lists.Count > 0)
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(lists));
                else
                    return CommonLog.MsgErrorInfo("没有任何数据");
            }
            catch (Exception ee)
            {
                return CommonLog.MsgErrorInfo("查询失败,原因：" + ee.Message);
            }
        }
        /// <summary>
        /// 通用单个对象查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="tttagKey"></param>
        /// <returns></returns>
        private static string GetObjFunc<T>(string sql, string param, string tttagKey) where T : BaseEntity
        {
           var listStr= GetListFunc<T>( sql,  param,  tttagKey);
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(listStr);
            if (!_param.GetBool("msgcode"))
                return listStr;
            else
            {
                List<T> list = JsonConvert.DeserializeObject<List<T>>(_param["msginfo"].ToString());
                return JsonConvert.SerializeObject(list[0]);
            }
        }
        #endregion 此处存放首页特定栏目相关的函数 end 


        #region 分享场景相关
        public string GetScene(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            return GetListFunc<Scene>("Shared_Scene.GetScenes", param, tttagKey);
        }


        public string EditScene(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Scene>(param, edit);
        }
        public string DelScene(string param)
        {
            string resultMsg = ExeMethodCheckParam(out bool isFail, param);
            if (isFail)
                return resultMsg;
            return OperateFunc<Scene>(param, del);
        }
        public string AddScene(string param)
        {
            //string resultMsg = ExeMethodCheckParam(out bool isFail, param, "SceneContent", stringStr);
            //if (isFail)
            //    return resultMsg;
            return OperateFunc<Scene>(param, add);
        }
        #endregion 分享场景相关 end



        #region 现货增删改查
        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string AddProductData(string strParam)
        {
            var logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam, "零售一级新增现货new");
            if (hsParam.ContainsKey("GoodsType"))
            {
                int goodsType = hsParam.GetInt("GoodsType").Value;
                hsParam.Remove("GoodsType");
                hsParam.Remove("SecondSN");
                if (hsParam.ContainsKey("GoldPrice"))
                    hsParam.Remove("GoldPrice");
                strParam = JsonConvert.SerializeObject(hsParam);
                return CRetails.AddProductData(strParam, tttagKey, goodsType);
            }
            else
            {
                return CommonLog.MsgErrorInfo("未指定商品类别");
            }
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string DelProductData(string strParam)
        {
            return CRetails.DelProductData(strParam);
        }
        /// <summary>
        /// 现货修改
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string ModifyProductData(string strParam)
        {
            return CRetails.ModifyProductData(strParam);
        }
        /// <summary>
        /// 货品查询
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetProductData(string strParam, string key)
        {
            logParam = strParam;
            string _msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\",\"data\":#result}";
            string tttagKey = string.Empty;
            string secondSn = string.Empty;
            Hashtable hsParam = Json.Deserialize<Hashtable>(strParam);
            {
                var open_Interface = string.Empty;
                if (key == "open_Interface")  //开放平台接口使用
                {
                    open_Interface = key;
                    key = "";
                    secondSn = hsParam["SecondSN"].ToString();//二级的供应商
                    hsParam.Remove("SecondSN");
                }
                if (!string.IsNullOrEmpty(key))
                {
                    tttagKey = key;
                }
                else
                {
                    tttagKey = CommonUrl.getURL(null, strParam);
                }
            }
            if (!hsParam.ContainsKey("useDict"))
                hsParam.Add("useDict", true);
            int goodsType = 0;
            try
            {
                CustomerInfo customer = null;
                //市场倍率
                //SetProductMarketDiscounts setProductMarketDiscounts = YZ.GetDatabase(tttagKey).QueryForObject<SetProductMarketDiscounts>("ProductMarketDiscounts.GetProductMarketDiscounts", null);
                if (hsParam.ContainsKey("CustomerID") && hsParam["CustomerID"].ToString() != "")
                {
                    customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(int.Parse(hsParam["CustomerID"].ToString()));
                }
                #region 客户对应的供应商权限
                if (customer != null && customer.RoleNames != null && customer.RoleNames != "")  //如果有供应商的权限
                {
                    Hashtable table = new Hashtable();
                    table.Add("RoleNames", customer.RoleNames.TrimEnd(',').Split(','));
                    table.Add("GoodsType", hsParam["GoodsType"].ToString());
                    var supplierNameList = YZ.GetDatabase(tttagKey).QueryForList<string>("Supplier.GetSupplierNameBySupplierNames", table);
                    if (supplierNameList.Count > 0)
                    {
                        //未添加任何供应商的参数，展示所有角色包含的供应商
                        if (hsParam.ContainsKey("Supplier") && hsParam["Supplier"].ToString() == "")
                        {
                            hsParam["Supplier"] = supplierNameList.ToArray();
                        }
                        else
                        {
                            bool isInRole = false;
                            foreach (var supplierName in supplierNameList)
                            {
                                //如果传的供应商在角色里面
                                if (hsParam["Supplier"].ToString() == supplierName)
                                {
                                    isInRole = !isInRole;
                                    break;
                                }
                            }
                            if (!isInRole)
                            {
                                //不在角色里面的供应商请求直接返回没有库存
                                return _msgInfo.Replace("#code", "false").Replace("#msg", "没有对应供应商的库存").Replace("#result", JsonConvert.SerializeObject(""));
                            }
                        }
                    }
                }
                #endregion


                string httpUrl = "";
                if (hsParam.ContainsKey("GoodsType"))
                {
                    goodsType = Convert.ToInt32(hsParam["GoodsType"].ToString());
                    hsParam.Remove("GoodsType");
                    strParam = JsonConvert.SerializeObject(hsParam);
                    if (goodsType == GoodsType.Parcel)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Parcel);
                        return GetProduct<ParcelInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Parcel, customer, secondSn);
                    }
                    else if (goodsType == GoodsType.Ring)
                    {
                        if (hsParam.ContainsKey("between"))
                        {
                            SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Ring, GoodsType.Ring, tttagKey);
                            decimal settingRate = 1;
                            decimal disc = 1;
                            aaaaaaaa bt = JsonConvert.DeserializeObject<aaaaaaaa>(strParam);
                            if (bt.between.Price != null)
                            {
                                for (int i = 0; i < bt.between.Price.Length; i++)
                                {
                                    settingRate = GetGroupAmount(settingInfo, (int.Parse(bt.between.Price[i][1]) - 1));
                                    disc = settingRate;
                                    bt.between.Price[i][0] = (Math.Round(int.Parse(bt.between.Price[i][0]) / disc)).ToString();
                                    bt.between.Price[i][1] = (Math.Round(int.Parse(bt.between.Price[i][1]) / disc)).ToString();
                                }
                                hsParam["between"] = bt.between;
                                strParam = JsonConvert.SerializeObject(hsParam);
                            }
                        }
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Ring);
                        return GetProduct<RingInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Ring, customer, secondSn);
                    }
                    else if (goodsType == GoodsType.Gem)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Gem);
                        return GetProduct<GemInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Gem, customer, secondSn);
                    }
                    else if (goodsType == GoodsType.Emerald)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Emerald);
                        return GetProduct<EmeraldInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Emerald, customer, secondSn);
                    }
                    else if (goodsType == GoodsType.PrimeGolds)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.PrimeGolds);
                        return GetProduct<PrimeGoldsInfoResult>(tttagKey, strParam, httpUrl, GoodsType.PrimeGolds, customer, secondSn);
                    }
                    else if (goodsType == GoodsType.InlaySettings)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.InlaySettings);
                        return GetProduct<InlaySettingsResult>(tttagKey, strParam, httpUrl, GoodsType.InlaySettings, customer, secondSn);
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                return "";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex, logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 货品查询
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetProductDataCount(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            hsParam.Add("PageCount", 0);  //这个很重要，拿返回总数一定要设置为0
            hsParam.Add("onlyCount", true);
            if (!hsParam.ContainsKey("useDict"))
                hsParam.Add("useDict", true);
            int goodsType = 0;
            try
            {
                CustomerInfo customer = null;
                //市场倍率
                SetProductMarketDiscounts setProductMarketDiscounts = YZ.GetDatabase(tttagKey).QueryForObject<SetProductMarketDiscounts>("ProductMarketDiscounts.GetProductMarketDiscounts", null);
                if (hsParam.ContainsKey("CustomerID") && hsParam.GetString("CustomerID") != "")
                {
                    customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(int.Parse(hsParam["CustomerID"].ToString()));
                }
                string httpUrl = "";
                if (hsParam.ContainsKey("GoodsType"))
                {
                    goodsType = hsParam.GetInt("GoodsType").Value;
                    hsParam.Remove("GoodsType");
                    strParam = JsonConvert.SerializeObject(hsParam);
                    if (goodsType == GoodsType.Parcel)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Parcel);
                        return GetProduct<ParcelInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Parcel);
                    }
                    else if (goodsType == GoodsType.Ring)
                    {
                        if (hsParam.ContainsKey("between"))
                        {
                            SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Ring, GoodsType.Ring, tttagKey);
                            decimal settingRate = 1;
                            decimal disc = 1;
                            aaaaaaaa bt = JsonConvert.DeserializeObject<aaaaaaaa>(strParam);
                            if (bt.between.Price != null)
                            {
                                for (int i = 0; i < bt.between.Price.Length; i++)
                                {
                                    settingRate = GetGroupAmount(settingInfo, (int.Parse(bt.between.Price[i][1]) - 1));
                                    if (setProductMarketDiscounts != null)
                                    {
                                        disc = settingRate * setProductMarketDiscounts.RingRebate;
                                    }
                                    else
                                    {
                                        disc = settingRate;
                                    }
                                    bt.between.Price[i][0] = (Math.Round(int.Parse(bt.between.Price[i][0]) / disc)).ToString();
                                    bt.between.Price[i][1] = (Math.Round(int.Parse(bt.between.Price[i][1]) / disc)).ToString();
                                }
                                hsParam["between"] = bt.between;
                                strParam = JsonConvert.SerializeObject(hsParam);
                            }
                        }
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Ring);
                        return GetProduct<RingInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Ring);
                    }
                    else if (goodsType == GoodsType.Gem)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Gem);
                        return GetProduct<GemInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Gem);
                    }
                    else if (goodsType == GoodsType.Emerald)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.Emerald);
                        return GetProduct<EmeraldInfoResult>(tttagKey, strParam, httpUrl, GoodsType.Emerald);
                    }
                    else if (goodsType == GoodsType.PrimeGolds)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.PrimeGolds);
                        return GetProduct<PrimeGoldsInfoResult>(tttagKey, strParam, httpUrl, GoodsType.PrimeGolds);
                    }
                    else if (goodsType == GoodsType.InlaySettings)
                    {
                        httpUrl = GoodsType.GetGoodsURL(GoodsType.InlaySettings);
                        return GetProduct<InlaySettingsResult>(tttagKey, strParam, httpUrl, GoodsType.InlaySettings);
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                return "";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex, logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        /// <summary>
        /// 查询单个明细
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetProductDataById(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            int goodsType = 0;
            try
            {
                string httpUrl = "";
                if (hsParam.ContainsKey("GoodsType"))
                {
                    string guid = Guid.NewGuid().ToString();
                    int totalSeconds;
                    string signStr;
                    MyHttpRequest.SignByParams(guid, "", tttagKey, out totalSeconds, out signStr);  //这里的id不是参数，所以签名不加入任何参数


                    goodsType = hsParam.GetInt("GoodsType").Value;
                    hsParam.Remove("GoodsType");
                    strParam = JsonConvert.SerializeObject(hsParam);
                    if (goodsType == GoodsType.Diamond)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.Diamond);
                    }
                    else if (goodsType == GoodsType.Parcel)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.Parcel);
                    }
                    else if (goodsType == GoodsType.Ring)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.Ring);
                    }
                    else if (goodsType == GoodsType.Gem)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.Gem);
                    }
                    else if (goodsType == GoodsType.Emerald)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.Emerald);
                    }
                    else if (goodsType == GoodsType.PrimeGolds)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.PrimeGolds);
                    }
                    else if (goodsType == GoodsType.InlaySettings)
                    {
                        httpUrl = GoodsType.GetGoodsUrlByTypId(hsParam.GetString("ID"), GoodsType.InlaySettings);
                    }

                    RequestInfo rif = new RequestInfo() { RequestJson = strParam, RequestUrl = httpUrl }; //需要更新地址中的ID
                    var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); //(Rapnet)
                    if (responseJson.Contains(".py"))
                    {
                        responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                    }
                    else
                    {
                        if (goodsType == GoodsType.Diamond)
                        {
                            InventoryInfo product = CalProductPrice<InventoryInfo>(hsParam, responseJson, GoodsType.Diamond, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.Parcel)
                        {
                            Parcels product = CalProductPrice<Parcels>(hsParam, responseJson, GoodsType.Parcel, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.Ring)
                        {
                            Ring product = CalProductPrice<Ring>(hsParam, responseJson, GoodsType.Ring, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.Gem)
                        {
                            Gem product = CalProductPrice<Gem>(hsParam, responseJson, GoodsType.Gem, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.Emerald)
                        {
                            Emerald product = CalProductPrice<Emerald>(hsParam, responseJson, GoodsType.Emerald, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.PrimeGolds)
                        {
                            PrimeGolds product = CalProductPrice<PrimeGolds>(hsParam, responseJson, GoodsType.PrimeGolds, tttagKey);
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }
                        else if (goodsType == GoodsType.InlaySettings)
                        {
                            InlaySettings product = CalProductPrice<InlaySettings>(hsParam, responseJson, GoodsType.InlaySettings, tttagKey);
                            decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, product.Supplier, goodsType);
                            //全局商品的倍率
                            SysSettingInfo setting = GetSystemSetting(GoodsType.InlaySettings, goodsType, tttagKey);

                            decimal CustomerRMB = (product.GoldPrice * product.NetGoldWeight * (1 + product.Wastage)) + product.SideLaborFee * product.SideNum + product.SidePrice + product.LaborFee + product.Insurance;
                            //decimal settingRate = GetGroupAmount(setting, CustomerRMB);
                            decimal settingRate = CRetails.GetGroupAmountByProduct(goodsType, setting.GroupAmount, CustomerRMB, tttagKey);
                            //客户的折扣 *全局商品的倍率 * 供应商的倍率 
                            product.Price = CustomerRMB * (1 + (supplierRate - 1) + (settingRate - 1));
                            responseJson = CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(product));
                        }

                    }
                    return responseJson;
                }
                else
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        /// <summary>
        /// 修改金价
        /// </summary>
        /// <param name="strParam"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string PutPrimeGoldsPrice(string strParam)
        {
            string tttagKey = CommonUrl.getURL(null, strParam);
            return CRetails.AllProduct(tttagKey, strParam, GlobalConfig.TransmissionPrimeGoldsPrice, "put");
        }
        /// <summary>
        /// 获取金价
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetPrimeGoldsPrice(string strParam)
        {
            string tttagKey = CommonUrl.getURL(null, strParam);
            return CRetails.AllProduct(tttagKey, strParam, GlobalConfig.TransmissionPrimeGoldsPrice, "get");
        }
        #endregion

        #region 现货批量修改
        /// <summary>
        /// 批量修改商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string ModifyProducts(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            try
            {
                #region 获取产品类别 和接口Url
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                int goodsType = hsParam.GetInt("GoodsType").Value;
                hsParam.Remove("GoodsType");
                strParam = JsonConvert.SerializeObject(hsParam);
                string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.TransmissionBatch, goodsType);
                #endregion
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = strParam, RequestUrl = filterUrl }
                         , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                );
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("数据远程服务错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("编辑，服务器内部错误");
            }
        }
        /// <summary>
        /// 批量修改商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string DelteProducts(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            try
            {
                #region 获取产品类别 和接口Url
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                int goodsType = hsParam.GetInt("GoodsType").Value;
                hsParam.Remove("GoodsType");
                strParam = JsonConvert.SerializeObject(hsParam);
                string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.TransmissionBatchDelete, goodsType);
                #endregion
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = strParam, RequestUrl = filterUrl }
                         , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST
                );
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("数据远程服务错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("编辑，服务器内部错误");
            }
        }
        /// <summary>
        /// 更新付款状态
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateProductPayStatus(string strParam)
        {
            return CRetails.UpdateProductPayStatus(strParam);
        }
        /// <summary>
        /// 批量改价
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string UpdateProductPrice(string strParam)
        {
            //前台传值统一参数名 免得混乱，新增与修改
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            try
            {
                #region 获取产品类别 和接口Url
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                int goodsType = hsParam.GetInt("GoodsType").Value;
                hsParam.Remove("GoodsType");
                strParam = JsonConvert.SerializeObject(hsParam);
                string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.TransmissionPrices, goodsType);
                #endregion
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = strParam, RequestUrl = filterUrl }
                         , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                );
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("数据远程服务错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("编辑，服务器内部错误");
            }
        }

        /// <summary>
        ///  上下架
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string ShelvesProducts(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            #region 获取产品类别 和接口Url
            if (!hsParam.ContainsKey("GoodsType"))
            {
                return CommonLog.MsgErrorInfo("未指定商品类别");
            }
            int goodsType = hsParam.GetInt("GoodsType").Value;
            hsParam.Remove("GoodsType");
            strParam = JsonConvert.SerializeObject(hsParam);
            string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.TransmissionBatch, goodsType);
            #endregion

            var partUrl = "";  //参数部分URL
            var lib = "0";//0白钻 ,1彩
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                var lastStr = "";
                //是否传参
                if (strParam != "")
                {
                    JObject obj = JsonConvert.DeserializeObject<JObject>(strParam);
                    lastStr = MyHttpRequest.NestedDictSort2Str(obj);
                    lib = obj["IsFancy"].ToString();
                    partUrl = "?IsFancy=" + lib;
                }
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);  // 
                RequestInfo rif = new RequestInfo() { RequestJson = strParam == "" ? "{}" : strParam, RequestUrl = string.Format(GlobalConfig.OnShelvesOrOffShelvesUrl, partUrl) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else if (responseJson.Contains("true"))
                {
                    responseJson = CommonLog.MsgSuccessInfo((lib == "0" ? "白钻" : "彩钻") + "上架成功");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo((partUrl == "" ? "全部" : lib == "0" ? "全部白钻" : "全部彩钻") + "上架失败，程序错误");
            }
        }
        #endregion

        #region 批量上传图片视频
        /// <summary>
        /// 批量上传图片视频
        /// </summary>
        /// <param name="imageParam"></param>
        /// <returns></returns>
        public UpFileResult UploadImagesAndVideos(ImageUploadMessage imageParam)
        {
            //#msg 和"#msg"
            UpFileResult result = new UpFileResult();
            if (imageParam.ImageDatas.Length == 0)
            {
                result.Message = "{\"msg\": \"noImgUpload\", \"successes\": [], \"result\": false, \"failures\": []}";//上传结果
                result.IsSuccess = false;
            }
            else
            {
                try
                {

                    string guid = Guid.NewGuid().ToString();
                    var type = imageParam.TypeName;
                    var RequestUrl = "";
                    if (imageParam.type == "img")
                        RequestUrl = string.Format(GlobalConfig.TransmissionImageUploadUrl, type, "?auto_matching=1&job_name=" + guid);
                    else if (imageParam.type == "video")
                        RequestUrl = string.Format(GlobalConfig.TransmissionVideoUploadUrl, type, "?auto_matching=1&job_name=" + guid);


                    Dictionary<string, object> postData = new Dictionary<string, object>();
                    postData.Add("auto_matching", 1); //加上
                    postData.Add("job_name", guid); //加上
                    int totalSeconds;
                    string signStr;
                    var lastStr = MyHttpRequest.ShotDic1(postData);
                    //签名
                    MyHttpRequest.SignByParams(guid, lastStr, imageParam.key, out totalSeconds, out signStr);
                    RequestInfo ri = new RequestInfo()
                    {
                        RequestUrl = RequestUrl // secondSn,有可能为二级提交
                    };
                    //发送带签名的参数
                    var httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");//保持长连接
                    using (var content = new MultipartFormDataContent())
                    {
                        for (int i = 0; i < imageParam.ImageDatas.Count(); i++)
                        {
                            //var fileContent = new StreamContent(imageParam.ImageDatas[i].ImageData);
                            var fileContent = new StreamContent(new MemoryStream(imageParam.ImageDatas[i].ImageData));
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = imageParam.ImageDatas[i].FileName, Name = "file_data" };
                            content.Add(fileContent);
                        }
                        content.Headers.Add("UUID", guid);
                        content.Headers.Add("Auth", signStr);
                        content.Headers.Add("Time", totalSeconds.ToString());
                        //提交数据中心
                        var responseJson = httpClient.PostAsync(RequestUrl, content)
                         .Result.Content.ReadAsStringAsync().Result;
                        result.Message = @responseJson.Replace("\"rows\":", "\"data\":");//上传结果
                        result.IsSuccess = JsonConvert.DeserializeObject<HashParam>(@responseJson).GetBool("result");
                    }
                }
                catch (Exception ex)
                {
                    GetMethodInfoAndWriteLogs(ex);
                    result.Message = "上传出错:程序错误";
                    result.IsSuccess = false;
                    return result;
                }
            }
            return result;
        }
        #endregion

        #region 获取市场倍率

        /// <summary>
        /// 获取市场倍率
        /// </summary>
        /// <returns></returns>
        public string GetMarketRate(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            SetProductMarketDiscounts setProductMarketDiscounts = YZ.GetDatabase(tttagKey).QueryForObject<SetProductMarketDiscounts>("ProductMarketDiscounts.GetProductMarketDiscounts", null);
            if (setProductMarketDiscounts != null)
            {
                return JsonConvert.SerializeObject(setProductMarketDiscounts);
            }
            else
            {
                setProductMarketDiscounts = new SetProductMarketDiscounts();
                setProductMarketDiscounts.Rebate = 1.2m;
                setProductMarketDiscounts.FancyRebate = 1.2m;
                setProductMarketDiscounts.ParcelRebate = 1.2m;
                setProductMarketDiscounts.RingRebate = 1.2m;
                setProductMarketDiscounts.GemRebate = 1.2m;
                setProductMarketDiscounts.EmeraldRebate = 1.2m;
                setProductMarketDiscounts.PrimeGoldRebate = 1.2m;
                setProductMarketDiscounts.InlaySettingsRebate = 1.2m;
                YZ.GetDatabase(tttagKey).Add(setProductMarketDiscounts);
                return JsonConvert.SerializeObject(setProductMarketDiscounts);
            }
        }
        /// <summary>
        /// 修改市场倍率
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string ModifyMarketRate(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "修改市场倍率");
            try
            {
                SetProductMarketDiscounts setRate = Json.Deserialize<SetProductMarketDiscounts>(strParam);
                int i = YZ.GetDatabase(tttagKey).Edit(setRate);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("修改成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("修改失败");
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：修改市场倍率" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        #endregion


        #region 客户定义DIY
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string AddCustomerMenu(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerMenu customerMenu = JsonConvert.DeserializeObject<CustomerMenu>(param);
                customerMenu.CreateTime = DateTime.Now;
                b = YZ.GetDatabase(tttagKey).Add(customerMenu) > 0;
                if (b)
                {
                    return "{\"message\":\"添加成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"添加失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string DelCustomerMenu(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerMenu customerMenu = JsonConvert.DeserializeObject<CustomerMenu>(param);
                b = YZ.GetDatabase(tttagKey).Delete("CustomerMenu.DeleteByID", customerMenu) > 0;
                if (b)
                {
                    return "{\"message\":\"删除成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"删除失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateCustomerMenu(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerMenu customerMenu = JsonConvert.DeserializeObject<CustomerMenu>(param);
                b = YZ.GetDatabase(tttagKey).Edit(customerMenu) > 0;
                if (b)
                {
                    return "{\"message\":\"修改成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"修改失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }
        /// <summary>
        /// 查
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetCustomerMenu(string strParam)
        {
            logParam = strParam;
            HashParam HsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(HsParam, strParam);
            IList<CustomerMenu> list = YZ.GetDatabase(tttagKey).QueryForList<CustomerMenu>("CustomerMenu.GetCustomerMenu", HsParam);
            if (list == null)
            {
                return CommonLog.MsgErrorInfo("没有用户自定义菜单");
            }
            else
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string AddCustomerDesign(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerDesign customerDesign = JsonConvert.DeserializeObject<CustomerDesign>(param);
                customerDesign.CreateTime = DateTime.Now;
                b = YZ.GetDatabase(tttagKey).Add(customerDesign) > 0;
                if (b)
                {
                    return "{\"message\":\"添加成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"添加失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string DelCustomerDesign(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerDesign link = JsonConvert.DeserializeObject<CustomerDesign>(param);
                b = YZ.GetDatabase(tttagKey).Delete("CustomerDesign.DeleteByID", link) > 0;
                if (b)
                {
                    return "{\"message\":\"删除成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"删除失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateCustomerDesign(string param)
        {
            logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            bool b = false;
            try
            {
                CustomerDesign link = JsonConvert.DeserializeObject<CustomerDesign>(param);
                b = YZ.GetDatabase(tttagKey).Edit(link) > 0;
                if (b)
                {
                    return "{\"message\":\"修改成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"修改失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }
        /// <summary>
        /// 查
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetCustomerDesign(string strParam)
        {
            logParam = strParam;
            HashParam HsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(HsParam, strParam);
            IList<CustomerDesign> list = YZ.GetDatabase(tttagKey).QueryForList<CustomerDesign>("CustomerDesign.GetCustomerDesign", HsParam);
            if (list == null)
            {
                return CommonLog.MsgErrorInfo("没有用户自定义信息");
            }
            else
            {
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
            }
        }
        #endregion

        #region 查询所有商品库存
        /// <summary>
        /// 查询所有商品库存 TAG
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public string GetAllProducts(string strParam)
        {
            logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            string searchUrl = "";
            try
            {
                //默认写死Tag 
                string param = "{\"filter\":{\"Tag\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"],\"useDict\":true}}";
                searchUrl = GlobalConfig.GetAllProductsURL;
                var result = CRetails.AllProduct(tttagKey, param, searchUrl, "post");
                result = result.Replace("rows_prime-golds", "rows_prime_golds").Replace("rows_inlay-settings", "rows_inlay_settings");
                if (hsParam != null && hsParam.ContainsKey("CustomerID") && hsParam.GetString("CustomerID") != "")
                {
                    AllProductList list = Json.Deserialize<AllProductList>(result);
                    CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(hsParam.GetInt("CustomerID"));
                    if (list.result && customer != null)
                    {
                        return CalcAllProducts(tttagKey, list, customer).Result;
                    }
                    else return result;
                }
                else
                {
                    return result;
                }

            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex, searchUrl);
                Logger.Error(this.GetType(), "异常" + ex.Message + "           " + "URL:" + GlobalConfig.GetAllProductsURL);
                throw;
            }

        }
        public async Task<string> CalcAllProducts(string tttagKey, AllProductList list, CustomerInfo customerInfo)
        {
            if (list.result)
            {
                list.rows_stocks = await CalcStocks(list.rows_stocks, customerInfo, tttagKey);
                list.rows_parcels = await CalcParcels(list.rows_parcels, customerInfo, tttagKey);
                list.rows_inlays = await CalcRing(list.rows_inlays, customerInfo, tttagKey);
                list.rows_gems = await CalcGem(list.rows_gems, customerInfo, tttagKey);
                list.rows_emeralds = await CalcEmerald(list.rows_emeralds, customerInfo, tttagKey);
                list.rows_prime_golds = await CalcPrimeGolds(list.rows_prime_golds, customerInfo, tttagKey);
                list.rows_inlay_settings = await CalcInlaySettings(list.rows_inlay_settings, customerInfo, tttagKey);
            }
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        /// 计算裸钻
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<InventoryInfoResult>> CalcStocks(List<InventoryInfoResult> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
               {
                   //全局商品的倍率 
                   SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Diamond, GoodsType.Diamond, tttagKey);
                   foreach (var item in list)
                   {
                       DiamondsPriceHandler.ComputePrice(tttagKey, item, settingInfo, customerInfo);
                   }
                   return list;
               });
            }
            return list;
        }
        /// <summary>
        /// 计算统包
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<Parcels>> CalcParcels(List<Parcels> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {

                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Parcel, GoodsType.Parcel, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = GetGroupAmount(settingInfo, item.Price);
                        //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.Parcel);
                        //客户的倍率
                        decimal customerRate = customerInfo.ParcelRebate.Value;
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
        /// <summary>
        /// 计算成品
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<Ring>> CalcRing(List<Ring> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {
                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Ring, GoodsType.Ring, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = GetGroupAmount(settingInfo, item.Price);
                        //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.Ring);
                        //客户的倍率
                        decimal customerRate = customerInfo.RingRebate.Value;
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
        /// <summary>
        /// 计算彩宝
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<Gem>> CalcGem(List<Gem> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {
                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Gem, GoodsType.Gem, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = GetGroupAmount(settingInfo, item.Price);
                        //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.Gem);
                        //客户的倍率
                        decimal customerRate = customerInfo.GemRebate.Value;
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
        /// <summary>
        /// 计算翡翠
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<Emerald>> CalcEmerald(List<Emerald> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {
                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.Emerald, GoodsType.Emerald, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = GetGroupAmount(settingInfo, item.Price);
                        //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.Emerald);
                        //客户的倍率
                        decimal customerRate = customerInfo.EmeraldRebate.Value;
                        item.Price = item.Price * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
        /// <summary>
        /// 计算素金
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<PrimeGolds>> CalcPrimeGolds(List<PrimeGolds> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {
                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.PrimeGolds, GoodsType.PrimeGolds, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = 1;// GetGroupAmount(settingInfo, item.Price);
                                                //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.PrimeGolds);
                        //客户的倍率
                        decimal customerRate = customerInfo.PrimeGoldRebate.Value;
                        item.Price = item.TotalWeight * (item.GoldPrice + item.LaborFee) * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
        /// <summary>
        /// 计算空托
        /// </summary>
        /// <param name="list"></param>
        /// <param name="customerInfo"></param>
        /// <returns></returns>
        public async Task<List<InlaySettings>> CalcInlaySettings(List<InlaySettings> list, CustomerInfo customerInfo, string tttagKey)
        {
            if (list.Count > 0)
            {
                return await Task.Run(() =>
                {
                    //全局商品的倍率 
                    SysSettingInfo settingInfo = GetSystemSetting(GoodsType.InlaySettings, GoodsType.InlaySettings, tttagKey);
                    foreach (var item in list)
                    {
                        //全局商品的倍率
                        decimal settingRate = 1;// GetGroupAmount(settingInfo, item.Price);
                                                //供应商的倍率
                        decimal supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, GoodsType.InlaySettings);
                        //客户的倍率
                        decimal customerRate = Convert.ToDecimal(customerInfo.InlaySettingsRebate);
                        item.Price = ((item.GoldPrice * item.NetGoldWeight * (1 + item.Wastage)) + item.SideLaborFee * item.SideNum + item.SidePrice + item.LaborFee + item.Insurance) * settingRate * supplierRate * customerRate;
                    }
                    return list;
                });
            }
            return list;
        }
 

        #endregion


        #region 设置客户登录方式和代下单的倍率 设置推荐
        public string AddLoginMode(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "添加客户登录方式");
            try
            {
                SetLoginMode param = Json.Deserialize<SetLoginMode>(strParam);
                SetLoginMode setLoginMode = YZ.GetDatabase(tttagKey).QueryForObject<SetLoginMode>("LoginMode.GetLoginMode", null);
                if (setLoginMode == null)
                {
                    param.CreateTime = DateTime.Now;
                    param.CreateUserID = pp.GetInt("UserID").Value;
                    int i = YZ.GetDatabase(tttagKey).Add(param);
                    if (i > 0)
                    {
                        return CommonLog.MsgSuccessInfo("添加成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加失败");
                    }
                }
                else
                {
                    setLoginMode.LoginMode = pp.GetInt("LoginMode");
                    setLoginMode.ModifyTime = DateTime.Now;
                    setLoginMode.ModifyUserID = pp.GetInt("UserID").Value;
                    int i = YZ.GetDatabase(tttagKey).Edit(setLoginMode);
                    if (i > 0)
                    {
                        return CommonLog.MsgSuccessInfo("修改成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败");
                    }
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：添加客户登录方式" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string GetLoginMode(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam);
            try
            {
                SetLoginMode setLoginMode = YZ.GetDatabase(tttagKey).QueryForObject<SetLoginMode>("LoginMode.GetLoginMode", null);

                if (setLoginMode != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(setLoginMode));
                }
                else
                {
                    setLoginMode = new SetLoginMode();
                    setLoginMode.LoginMode = 0;//默认账号和短信登陆都要
                    return CommonLog.MsgObj(false,JsonConvert.SerializeObject(setLoginMode));
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        public string ModifyLoginMode(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "修改客户登录方式");
            try
            {
                SetLoginMode setLoginMode = Json.Deserialize<SetLoginMode>(strParam);
                setLoginMode.ModifyTime = DateTime.Now;
                setLoginMode.ModifyUserID = pp.GetInt("UserID").Value;
                int i = YZ.GetDatabase(tttagKey).Edit(setLoginMode);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("修改成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("修改失败");
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：修改客户登录方式" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string AddOrderRate(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "添加代下单的倍率");
            try
            {
                SetOrderRate param = Json.Deserialize<SetOrderRate>(strParam);
                SetOrderRate setOrderRate = YZ.GetDatabase(tttagKey).QueryForObject<SetOrderRate>("OrderRate.GetOrderRate", null);
                if (setOrderRate == null)
                {
                    param.CreateTime = DateTime.Now;
                    param.CreateUserID = pp.GetInt("UserID").Value;
                    int i = YZ.GetDatabase(tttagKey).Add(param);
                    if (i > 0)
                    {
                        return CommonLog.MsgSuccessInfo("添加成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加失败");
                    }
                }
                else
                {
                    setOrderRate.IsRate = pp.GetInt("IsRate");
                    setOrderRate.SetRate = pp.GetInt("SetRate").Value;
                    setOrderRate.ModifyTime = DateTime.Now;
                    setOrderRate.ModifyUserID = pp.GetInt("UserID").Value;
                    int i = YZ.GetDatabase(tttagKey).Edit(setOrderRate);
                    if (i > 0)
                    {
                        return CommonLog.MsgSuccessInfo("修改成功");
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败");
                    }
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：添加代下单的倍率" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string GetOrderRate(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam);
            try
            {
                SetOrderRate setOrderRate = YZ.GetDatabase(tttagKey).QueryForObject<SetOrderRate>("OrderRate.GetOrderRate", null);

                if (setOrderRate != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(setOrderRate));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请先设置代下单倍率");
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        public string ModifyOrderRate(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "修改代下单的倍率");
            try
            {
                SetOrderRate setOrderRate = Json.Deserialize<SetOrderRate>(strParam);
                setOrderRate.ModifyTime = DateTime.Now;
                setOrderRate.ModifyUserID = pp.GetInt("UserID").Value;
                int i = YZ.GetDatabase(tttagKey).Edit(setOrderRate);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("修改成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("修改失败");
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：修改代下单的倍率" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string AddRecommend(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "添加推荐设置");
            try
            {
                SetRecommend param = Json.Deserialize<SetRecommend>(strParam);

                param.CreateTime = DateTime.Now;
                param.CreateUserID = pp.GetInt("UserID").Value;
                int i = YZ.GetDatabase(tttagKey).Add(param);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("添加成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("添加失败");
                }

            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：添加推荐设置" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string DelRecommend(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "删除推荐设置");
            try
            {

                int i = YZ.GetDatabase(tttagKey).Delete("Recommend.DelRecommend", pp);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("删除成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("删除失败");
                }

            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：删除推荐设置" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        public string GetRecommend(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam);
            try
            {
                IList<SetRecommend> list = YZ.GetDatabase(tttagKey).QueryForList<SetRecommend>("Recommend.GetRecommend", null);

                if (list.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(list));
                }
                else
                {
                    return CommonLog.MsgErrorInfo("请先设置推荐名称");
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        public string ModifyRecommend(string strParam)
        {
            HashParam pp = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(pp, strParam, "修改推荐设置");
            try
            {
                SetRecommend setRecommend = Json.Deserialize<SetRecommend>(strParam);
                setRecommend.ModifyTime = DateTime.Now;
                setRecommend.ModifyUserID = pp.GetInt("UserID").Value;
                int i = YZ.GetDatabase(tttagKey).Edit(setRecommend);
                if (i > 0)
                {
                    return CommonLog.MsgSuccessInfo("修改成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("修改失败");
                }
            }
            catch (Exception ex)
            {
                SendMQMsg(tttagKey, "异常信息：修改推荐设置" + ex.StackTrace + "参数：" + strParam);
                throw;
            }
        }
        /// <summary>
        /// 复核，直接调用一级的函数
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        #endregion
        public  string ReVerify(string param)
        {
            return CWholesalers.ReVerify(param);
        }


        #region  小程序相关 
   
        /// <summary>
        /// 绑定客户信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string BindByParam(string customerAndOpenId, string key)
        {
            int flag = 2; //标识是绑定团队还是客户，目前批发系统为客户1，零售为绑定团队2
            return AllPublic.BindByParam(customerAndOpenId, key, flag);
        }
        /// 分享的用户绑定到指定业务
        public string BindSalesByOpenId(string bindParam,string key)
        {
            HashParam param = JsonConvert.DeserializeObject<HashParam>(bindParam);
            if (!param.ContainsKey("OpenId") && !param.ContainsKey("UserId"))
            {
                return CommonLog.MsgErrorInfo("OpenId ,UserId 不能为空");
            }
            var openId = param.GetString("OpenId", "");
            var userId = param.GetInt("UserId", 0);
            if (openId == "" || userId == 0)
                return CommonLog.MsgErrorInfo($"用户信息不正确");
            
            //账号正确的话就开始绑定 
            var wxInfo =AllPublic.GetWxUserByOpenid(new WechatXcxInfo() { openid = param.GetString("OpenId") }, key);
            if (wxInfo == null)
                return CommonLog.MsgErrorInfo("用户未保存不能进行绑定");
            //return AllPublic.BindByParam(customerAndOpenId, key, flag);
            //判断绑定的id是否存在
            var userInfo = YZ.GetDatabase(key).Get<UserInfo>(userId);
            if (userInfo == null)
            {
                return CommonLog.MsgErrorInfo("UserInfo 不能为空");
            }
            wxInfo.flag = 2;//绑定团队
            wxInfo.customer_id = userId;
            wxInfo.bind_time = DateTime.Now;
            int result = YZ.GetDatabase(key).Edit(wxInfo);
            if (result > 0)
                return CommonLog.MsgSuccessInfo("绑定成功");
            else
                return CommonLog.MsgErrorInfo("绑定失败");

        }
        #endregion
    }
}
